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
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()
.
Use indexof to find the index of the item.
list.remove(list.indexOf(300));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With