What will be the contents of the list after following operation and why?

Description:

final List<Integer> list = new ArrayList<>();

list.add(1);
list.add(2);
list.add(3);

list.remove(2);

Solution:

The contents will be:

[ 1, 2 ]

The reason is that there are two removal operations on a List:

  • remove(int index)
  • remove(Object obj)

The JVM will always select the most specific overload of a method; and here we pass an int as an argument, the code therefore removes the element at index 2.

To remove the element 2 from the list, the following needs to be written:

list.remove(Integer.valueOf(2));
0 answers