Here\'s a nice pitfall I just encountered. Consider a list of integers:
List list = new ArrayList();
list.add(5);
list.add(6);
Well here is the trick.
Let's take two examples here:
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);
}
}
Now let's have a look at the output:
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]
Now let's analyze the output:
When 3 is removed from the collection it calls the remove()
method of the collection which takes Object o
as parameter. Hence it removes the object 3
.
But in arrayList object it is overridden by index 3 and hence the 4th element is removed.
By the same logic of Object removal null is removed in both cases in the second output.
So to remove the number 3
which is an object we will explicitly need to pass 3 as an object
.
And that can be done by casting or wrapping using the wrapper class Integer
.
Eg:
Integer removeIndex = Integer.valueOf("3");
collection.remove(removeIndex);