Reputation: 361
imagine the following ArrayList in Java:
ArrayList<Integer> u = new ArrayList<Integer>();
I want to know if there is a difference when adding new values either as primitive types or as wrapper-classes:
u.add(new Integer(12));
u.add(12);
Thanks in advance!
Upvotes: 0
Views: 2604
Reputation: 54074
There is no difference in add
due to auto boxing/unboxing. Actually don't do new Integer(12)
but Integer.valueOf(12)
since it uses the flighweight pattern and reuses known objects (in the range -128, 127). So no new object would be created.
There is a difference in remove
for example.
Since if you intent to call remove(Object)
calling remove(5)
will call remove(int index)
and this perhaps is not what you want.
You should do remove((Integer)5)
if you want to remove the number 5
or remove(5)
if you want to remove the fifth element.
Upvotes: 8
Reputation: 4342
When you do u.add(12);
compiler rewrites it to u.add(Integer.valueOf(12));
which is more efficient than u.add(new Integer(12));
Read more on official tutorial http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
Upvotes: 7