Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove integer from list? [duplicate]

Tags:

java

arraylist

I need to remove integer from integer arraylist. I have no problem with strings and other objects. But when i removing, integer is treated as an index instead of object.

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(300);
list.remove(300);

When I am trying to remove 300 i am getting: 06-11 06:05:48.576: E/AndroidRuntime(856): java.lang.IndexOutOfBoundsException: Invalid index 300, size is 3

like image 287
Yarh Avatar asked Jun 11 '13 06:06

Yarh


2 Answers

This is normal, there are two versions of the .remove() method for lists: one which takes an integer as an argument and removes the entry at this index, the other which takes a generic type as an argument (which, at runtime, is an Object) and removes it from the list.

And the lookup mechanism for methods always picks the more specific method first...

You need to:

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

in order to call the correct version of .remove().

like image 114
fge Avatar answered Sep 26 '22 00:09

fge


Use indexof to find the index of the item.

list.remove(list.indexOf(300));
like image 41
SBI Avatar answered Sep 27 '22 00:09

SBI