Consider the following code:
import java.util.ArrayList;
public class ArrayListOperations {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(2);
numbers.add(4);
numbers.add(6);
numbers.add(8);
numbers.add(10);
numbers.add(2, 20);
numbers.remove(3);
System.out.println(numbers.get(1));
System.out.println(numbers.size());
System.out.println(numbers.contains(4));
}
}
What is the output of the above code?
Explain each step of the code and how the ArrayList operations affect the elements stored in the ArrayList.
The output of the code is:
4
5
true
Explanation:
The ArrayList numbers
is created and initialized with values [2, 4, 6, 8, 10]
using the numbers.add()
method.
The numbers.add(2, 20)
operation adds the element 20
at index 2
. After this operation, the ArrayList numbers
becomes [2, 4, 20, 6, 8, 10]
.
The numbers.remove(3)
operation removes the element at index 3
. After this operation, the ArrayList numbers
becomes [2, 4, 20, 8, 10]
.
The numbers.get(1)
operation retrieves the element at index 1
, which is 4
. This value is printed to the console.
The numbers.size()
operation returns the size of the ArrayList, which is 5
. This value is printed to the console.
The numbers.contains(4)
operation checks if the ArrayList contains the element 4
. Since 4
is present in the ArrayList, the contains
method returns true
. This value is printed to the console.
Thus, the output of the code is 4
, 5
, true
.