Search code examples
javaarraylistprimitive

Java ArrayList: Adding primitive type or its wrapper-class: What's the difference?


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!


Solution

  • 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