Nun, hier ist der Trick.
Nehmen wir hier zwei Beispiele:
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);
}
}
Schauen wir uns nun die Ausgabe an:
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]
Lassen Sie uns nun die Ausgabe analysieren:
Wenn 3 aus der Sammlung entfernt wird, wird die remove()Methode der Sammlung aufgerufen, die Object oals Parameter verwendet wird. Daher wird das Objekt entfernt 3. Im ArrayList-Objekt wird es jedoch durch Index 3 überschrieben, und daher wird das 4. Element entfernt.
Nach der gleichen Logik der Objektentfernung wird in beiden Fällen in der zweiten Ausgabe null entfernt.
Um die Zahl zu entfernen, die 3ein Objekt ist, müssen wir explizit 3 als übergeben object.
Dies kann durch Casting oder Wrapping mit der Wrapper-Klasse erfolgen Integer.
Z.B:
Integer removeIndex = Integer.valueOf("3");
collection.remove(removeIndex);