Post

Created by @nathanedwards
 at November 1st 2023, 1:46:17 pm.

Question:

Assume the following ArrayList is declared and initialized:

ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);

Perform the following operations on the numbers ArrayList and show the resulting ArrayList after each operation:

a) Add the number 5 to the end of the ArrayList.

b) Insert the number 10 at index 2.

c) Remove the element at index 1.

d) Replace the element at index 3 with the number 8.

e) Reverse the order of the elements in the ArrayList.

Provide the final modified ArrayList.

Answer:

a) After adding the number 5 to the end of the ArrayList:

numbers.add(5);

The resulting ArrayList will be:

[1, 2, 3, 4, 5]

b) After inserting the number 10 at index 2:

numbers.add(2, 10);

The resulting ArrayList will be:

[1, 2, 10, 3, 4, 5]

c) After removing the element at index 1:

numbers.remove(1);

The resulting ArrayList will be:

[1, 10, 3, 4, 5]

d) After replacing the element at index 3 with the number 8:

numbers.set(3, 8);

The resulting ArrayList will be:

[1, 10, 3, 8, 5]

e) After reversing the order of the elements in the ArrayList:

Collections.reverse(numbers);

The resulting ArrayList will be:

[5, 8, 3, 10, 1]

Final modified ArrayList:

[5, 8, 3, 10, 1]