In the second case, can I be sure the right value will be deleted?
Yes you can.
The remove
method will use equals(Object)
to identify the object to be removed from the list. Since Integer.equals
compares by value (not by object identity), it doesn't matter how you created the Integer
instances ... provided the wrapped int
values are the same.
However ... your second version is inferior to the first version:
It cumbersome: 3 statements instead of 1.
You are using
new Integer(...)
rather thanInteger.valueOf(...)
which is always going to create a new instance. By contrast, autoboxing (or callingInteger.valueOf(...)
explicitly) makes use of theInteger
classes instance cache, and that will often avoid creating a new instance.