Collections · interview question
What does this print?
What does this code output?Medium
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(List.of(1, 2, 3));
list.remove(1);
System.out.println(list);
}
}Answer and explanation
Correct answer
A. [1, 3]
Why
remove(1) matches the overload remove(int index) (an exact primitive match beats boxing), so it removes the element at index 1, which is the value 2.
References
Test yourself on Collections
A free test with instant, explained results. No account needed.
More Collections questions
- Which interface should a class implement to define its natural ordering, so that Collections.sort(list) works without…
- If you need a collection that supports quick insertion and removal of elements at both ends, but also provides indexed…
- Why do teams use a HashSet over a List when storing items in production code?
- Which Java collection should you use if you need to store elements with fast random access and allow duplicates?
- Which collection does not allow duplicate elements?
- Which Java collection would you choose if you need to maintain insertion order and allow duplicates?