Zhenxiao Hao Zhenxiao Hao - 1 year ago 172
Java Question

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
.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download