这里有个诀窍。
让我们举两个例子:
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个元素被删除。
在第二个输出中,通过相同的对象删除逻辑,在两种情况下都删除null。
为了移除数字3这个对象我们需要显式地将3作为一个对象传递。
这可以通过使用包装器类Integer进行强制转换或包装来实现。
Eg:
Integer removeIndex = Integer.valueOf("3");
collection.remove(removeIndex);