Search code examples
javaautoboxing

Quick autoboxing/auto-unboxing question in Java


I was just introduced to the concept of autoboxing in Java and I have a couple of quick questions to help me clarify my understand. From what I understand is that when we declare an arraylist such as

ArrayList<Integer> myList = new ArrayList<Integer>();

we can still put primitive ints inside myList as the primitive will be automatically wrapped into an Integer object. I'm guessing this implies that if I tried to do add an Integer object to this ArrayList, there wouldn't be any autoboxing since I am adding the 'correct' type? In other words, I'm guessing the command

myList.add(new Integer(2));

doesn't use any autoboxing. Similarly, I'm guessing that retrieving elements from this ArrayList and storing them in their wrappers does not require autoboxing since I'm not placing them in their primitives? Aka:

Integer a = myList.get(0);

does not unbox? From what I understand, unboxing will occur when I try to mix primitives into the picture:

int b = 4;
Integer c = a + b;

In a situation like this, I think a will auto-unbox into an int primitive, add with the int b and then auto-box itself into an integer object? Is my understanding on the right track?


Solution

  • Your understanding is correct.

    People starting confusing Integer and int when autoboxing was introduced in Java 5 in 2004. Previous to that, you had to box and unbox explicitly. Autoboxing has advantages of more succinct code but also disadvantages that some novice programmers don't realise exactly what is happening and unwittingly write code that needlessly boxes and unboxes.

    By the way, your example of new Integer(2) is better coded as Integer.valueOf(2). The latter will use a cached object instead of creating a new one.