In my Java class, the professor uses something like:
integerBox.add(new Integer(10));
Is this the same as just doing:
integerBox.add(10);
?
I’ve googled a bit but can’t find out one way or the other, and the prof was vague.
The closest explanation I can find is this:
An int is a number; an Integer is a pointer that can reference an
object that contains a number.
Basically, Java collection classes like
Vector,ArrayList,HashMap, etc. don’t take primitive types, likeint.In the olden days (pre-Java 5), you could not do this:
You would have to do this:
This is because
10is just anintby itself.Integeris a class, that wraps theintprimitive, and making anew Integer()means you’re really making an object of typeInteger. Before autoboxing came around, you could not mixIntegerandintlike you do here.So the takeaway is:
integerBox.add(10)andintegerBox.add(new Integer(10))will result in anIntegerbeing added tointegerBox, but that’s only becauseintegerBox.add(10)transparently creates theIntegerfor you. Both ways may not necessarily create theIntegerthe same way, as one is explicitly being created withnew Integer, whereas autoboxing will useInteger.valueOf(). I am going by the assumption the tutorial makes thatintegerBoxis some type of collection (which takes objects, and not primitives).But in this light:
One is a primitive, the other is an object of type
Integer.