Java, how to remove an Integer item in an ArrayList

Suppose I have such an ArrayList:

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

After the adding operation:

list.add(2);
list.add(3);
list.add(5);
list.add(7);

I want to remove number 2, if I do

list.remove(2);

then number 5 will be deleted, how could I delete number 2? And suppose I don't know the index of number 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


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));