如何从列表中删除整数? [英] How to remove integer from list?
问题描述
我需要从整数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);
当我想删除300时,我得到:
06-11 06:05:48.576:E / AndroidRuntime(856):java.lang.IndexOutOfBoundsException:索引300无效,大小为3
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
推荐答案
这是正常的,列表有两个版本的 .remove()
方法:一个以整数作为参数的方法并删除此索引处的条目,另一个将泛型类型作为参数(在运行时,它是对象
)并将其从列表中删除。
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...
你需要:
list.remove(Integer.valueOf(300));
为了调用正确版本的 .remove()
。
这篇关于如何从列表中删除整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!