0

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!

1
  • Thanks for your explanations, I am feeling lucky now :) Commented Feb 16, 2013 at 20:52

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

7

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.