Java,如何删除数组列表中的整数项

假设我有这样一个数组列表:

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

After the adding operation:

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

如果需要,我想移除 number 2

list.remove(2);

那么 number 5就会被删除,我怎么能删除 number 2呢? 假设我不知道 number 2的索引。

92786 次浏览
list.remove(0);

0 represent element at index 0

而且您已经编写了 list.remove(2);,这意味着删除位于索引2的元素(即位于第三位的元素,即从 ArrayList开始使用索引0,1,2...)

试试这个

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

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

你也可以用这个

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

but it will remove only first occurence of 2

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

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

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

Be aware that indexOf returns the index of the 第一次出现 of the object you give it, so you'll have to adjust accordingly for cases where you want to delete an item that is in the list multiple times.

remove()方法有两种版本:

使用 ArrayList<Integer>时,除去像 2这样的整数值将被作为索引,因为 remove(int)与此完全匹配。它不会将 2框到 Integer,并将其扩大。

A workaround is to get an Integer object explicitly, in which case widening would be prefered over unboxing:

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

我想这就是你想要的: ArrayList <Integer> with the get/remove method

list.remove(new Integer(2));

试试这个:

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

试试看,

list.remove(0);
  1. 移除(int 索引)

    移除此列表中指定位置的元素(可选 operation). Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from 清单

  2. 移除(对象)

    中移除指定元素的第一个匹配项 如果该列表不包含该元素,则 is unchanged. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if 如果此列表包含 指定的元素(或者等效地,如果这个列表因此而改变 的电话)。

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

你的数组列表: 2,3,5,7

删除(2) ;

输出: 2,5,7

如果你像这样使用方法,它会移除值为2的元素

你的数组列表: 2,3,5,7

Remove (Integer.valueOf (2)) ;

输出: 3,5,7

希望对你有帮助。

而不是:

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

你当然可以只用:

list.remove((Integer) 2);

This will cast to an Integer object rather than primitive and then remove() by Object instead of Arraylist Index

You calling list.remove(int) method, but you need to call list.remove(Object) method.

有几种方法可以做到这一点:

  1. list.remove(Integer.valueOf(2)); // removes the first occurrence of 2
  2. list.remove(list.indexOf(2)); // also removes the first occurrence of 2
  3. list.removeAll(Arrays.asList(2)); // removes all occurrences of 2

最简单的方法是:

list.remove((Integer)5);

没有不必要的对象创建,只是将索引转换为整数。

在你的情况下,这也应该工作,

list.removeIf(element -> element == 2);

you can use list.remove(new Integer(i)) where i is the element you want to remove.