问题
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
回答1:
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()
.
回答2:
Use indexof to find the index of the item.
list.remove(list.indexOf(300));
回答3:
Try (passing an Integer
, object, instead of an int
, primitive) -
list.remove(Integer.valueOf(300));
to invoke the right method - List.remove(Object o)
回答4:
Please try below code to remove integer from list,
public static void main(String[] args) {
List<Integer> lIntegers = new ArrayList<Integer>();
lIntegers.add(1);
lIntegers.add(2);
lIntegers.add(300);
lIntegers.remove(new Integer(300));
System.out.println("TestClass.main()"+lIntegers);
}
If you remove item by passing primitive then it will take it as index and not value/object
回答5:
Use list.remove((Integer)300);
来源:https://stackoverflow.com/questions/17037583/how-to-remove-integer-from-list