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?