I understand that it is possible to add an Integer Object to an ArrayList
of type Integer
. That makes sense to me. Like this:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(new Integer(3));
But why is it possible to add a primitive datatype like int instead of Integer
? Like this:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
Why is that allowed??
This is called
autoboxing
. For classes that have corresponding primitives (e.g,Long
->long
,Integer
->int
), Java will handle the conversion for you.It should be noted this behavior comes with some dark corners:
null
is unboxed into a primitive, aNullPointerException
will be thrown, which might be unexpected for the programmer since it looks like a primitive is throwing the exception.