Java, how to remove an Integer item in an ArrayList

There are two versions of remove() method:

  • ArrayList#remove(Object) that takes an Object to remove, and
  • ArrayList#remove(int) that takes an index to remove.

With an ArrayList<Integer>, removing an integer value like 2, is taken as index, as remove(int) is an exact match for this. It won't box 2 to Integer, and widen it.

A workaround is to get an Integer object explicitly, in which case widening would be prefered over unboxing:

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

instead of:

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

you can of course just use:

list.remove((Integer) 2);

This will cast to an Integer object rather than primitive and then remove() by Object instead of Arraylist Index


I think this is what you want : ArrayList <Integer> with the get/remove method

list.remove(new Integer(2));

try this

list.removeAll(Arrays.asList(2));

it will remove all elements with value = 2

you can also use this

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

but it will remove only first occurence of 2

list.remove(2) does not work because it matches List.remove(int i) which removes element with the specified index

Tags:

Java