如何从列表中删除整数?

Yar*_*arh 9 java arraylist

我需要从整数arraylist中删除整数.我对字符串和其他对象没有任何问题.但是当我删除时,整数被视为索引而不是对象.

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(300);
list.remove(300);
Run Code Online (Sandbox Code Playgroud)

当我试图删除300我得到: 06-11 06:05:48.576: E/AndroidRuntime(856): java.lang.IndexOutOfBoundsException: Invalid index 300, size is 3

fge*_*fge 24

这是正常的,.remove()列表方法有两个版本:一个以整数作为参数并删除该索引处的条目,另一个将泛型类型作为参数(在运行时是一个Object)和将其从列表中删除.

并且方法的查找机制总是首先选择更具体的方法......

你需要:

list.remove(Integer.valueOf(300));
Run Code Online (Sandbox Code Playgroud)

为了调用正确的版本.remove().


SBI*_*SBI 11

使用indexof查找项的索引.

list.remove(list.indexOf(300));
Run Code Online (Sandbox Code Playgroud)

  • 虽然这确实有效,但执行起来比使用`Integer.valueOf`来获取对象要昂贵得多. (4认同)

Bhe*_*ung 5

尝试(传递Integer, 对象,而不是int, 原语)-

list.remove(Integer.valueOf(300));
Run Code Online (Sandbox Code Playgroud)

调用正确的方法 - List.remove(Object o)