这就是诀窍。
我们在这里举两个例子:
public class ArrayListExample {
public static void main(String[] args) {
Collection collection = new ArrayList<>();
List 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时,它调用集合的Integer方法,该方法将object作为参数。 因此它删除了对象3。但是在arrayList对象中,它被索引3覆盖,因此删除了第4个元素。
通过与Object删除相同的逻辑,在第二个输出中的两种情况下都会删除null。
因此,要删除号码Integer这是一个对象,我们将明确需要传递3作为object。
这可以通过使用包装器类Integer进行转换或包装来完成。
例如:
Integer removeIndex = Integer.valueOf("3");
collection.remove(removeIndex);