MCQ IN COMPUTER SCIENCE & ENGINEERING

COMPUTER SCIENCE AND ENGINEERING

DATA STRUCTURES

Question [CLICK ON ANY CHOICE TO KNOW THE RIGHT ANSWER]
Which is the right way to put 21 at the second position in an ArrayList of Integers? (Remember zero-indexing!)
A
list.put(2, 21);
B
list.add(1, 21);
C
list.add(2, 21);
D
list.add(21, 1);
Explanation: 

Detailed explanation-1: -The size of an ArrayList can be obtained by using the java. util. ArrayList. size() method as it returns the number of elements in the ArrayList i.e. the size.

Detailed explanation-2: -You can insert an element at a specific index from 0 to size() . The newly added element is now located at the specified index, and the indexes of all elements above that element is increased by one. If you add an element at index size(), the element is appended to the end of the list.

Detailed explanation-3: -The ArrayList index starts at 0 just like arrays, but instead of using the square brackets [] to access elements, you use the get(index) to get the value at the index and set(index, value) to set the element at an index to a new value.

There is 1 question to complete.