Java,如何删除ArrayList中的Integer项


78

假设我有这样一个ArrayList:

ArrayList<Integer> list = new ArrayList<Integer>();

添加操作后:

list.add(2);
list.add(3);
list.add(5);
list.add(7);

如果要删除number 2,我想删除

list.remove(2);

然后number 5将被删除,我该如何删除number 2?并且假设我不知道的索引number 2


Answers:


126

尝试这个

list.removeAll(Arrays.asList(2));

它将删除所有值= 2的元素

你也可以用这个

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

但它只会删除第一次出现的2

list.remove(2)不起作用,因为它匹配List.remove(int i)将删除具有指定索引的元素


26

方法有两种版本remove()

使用ArrayList<Integer>,删除一个整数值(例如2)作为索引,remove(int)与此完全匹配。它不会装箱2Integer并扩大它。

一种解决方法是Integer显式获取对象,在这种情况下,与取消装箱相比,应首选加宽:

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

8

代替:

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

您当然可以使用:

list.remove((Integer) 2);

这将强制转换为Integer对象而不是原始对象,然后转换remove()为Object而不是Arraylist索引



3

尝试这个:

list.remove(list.indexOf(2));

1

没有找到特定列表元素然后将其删除的显式方法。您必须首先使用indexOf方法找到它:

int index = list.indexOf(element); // for your example element would be 2
list.remove(index);

请注意,它会indexOf返回给定给您的对象的第一个匹配项的索引,因此对于要多次删除列表中项目的情况,您将必须进行相应的调整。


1

尝试,

list.remove(0);
  1. remove(int index)

    删除此列表中指定位置的元素(可选操作)。将所有后续元素向左移动(从其索引中减去一个)。返回从列表中删除的元素。

  2. remove(对象o)

    如果存在指定元素,则从该列表中删除该元素的第一次出现。如果列表不包含该元素,则该元素不变。更正式地讲,删除索引i最低的元素,使(o==null ? get(i)==null : o.equals(get(i)))(如果存在这样的元素)。如果此列表包含指定的元素,则返回true(或者等效地,如果此列表由于调用而更改),则返回true。


1

简单地说,如果您使用这样的方法,它将删除索引2处的元素

您的阵列列表:2,3,5,7

list.remove(2);

输出:2,5,7

如果使用这样的方法,它将删除值为2的元素

您的阵列列表:2,3,5,7

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

输出:3,5,7

希望对您有帮助...


-2
list.remove(0);

0代表索引0处的元素

并且您已经写了list.remove(2);这意味着在索引2处删除元素(即,从ArrayList索引0,1,2 ...开始,元素位于第三位,即5 )。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.