这就是诀窍。
我们这里举两个例子:
public class ArrayListExample {
public static void main(String[] args) {
Collection<Integer> collection = new ArrayList<>();
List<Integer> arrayList = new ArrayList<>();
collection.add(1);
collection.add(2);
collection.add(3);
collection.add(null);
collection.add(4);
collection.add(null);
System.out.println("Collection" + collection);
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(null);
arrayList.add(4);
arrayList.add(null);
System.out.println("ArrayList" + arrayList);
collection.remove(3);
arrayList.remove(3);
System.out.println("");
System.out.println("After Removal of '3' :");
System.out.println("Collection" + collection);
System.out.println("ArrayList" + arrayList);
collection.remove(null);
arrayList.remove(null);
System.out.println("");
System.out.println("After Removal of 'null': ");
System.out.println("Collection" + collection);
System.out.println("ArrayList" + arrayList);
}
}
现在让我们看看输出:
Collection[1, 2, 3, null, 4, null]
ArrayList[1, 2, 3, null, 4, null]
After Removal of '3' :
Collection[1, 2, null, 4, null]
ArrayList[1, 2, 3, 4, null]
After Removal of 'null':
Collection[1, 2, 4, null]
ArrayList[1, 2, 3, 4]
现在让我们分析一下输出:
当从集合中删除 3 时,它会调用集合的 remove() 方法,该方法以 Object o 作为参数。因此它删除了对象3。
但在 arrayList 对象中,它被索引 3 覆盖,因此第 4 个元素被删除。
通过对象移除的相同逻辑,在第二个输出中的两种情况下都会移除空值。
所以要删除数字 3 这是一个对象,我们需要明确地将 3 作为 object 传递。
这可以通过使用包装类Integer进行强制转换或包装来完成。
例如:
Integer removeIndex = Integer.valueOf("3");
collection.remove(removeIndex);