Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using new(Integer) versus an int

Tags:

java

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.

like image 576
Jeremy Avatar asked Dec 21 '22 09:12

Jeremy


1 Answers

Basically, Java collection classes like Vector, ArrayList, HashMap, etc. don't take primitive types, like int.

In the olden days (pre-Java 5), you could not do this:

List myList = new ArrayList();
myList.add(10);

You would have to do this:

List myList = new ArrayList();
myList.add(new Integer(10));

This is because 10 is just an int by itself. Integer is a class, that wraps the int primitive, and making a new Integer() means you're really making an object of type Integer. Before autoboxing came around, you could not mix Integer and int like you do here.

So the takeaway is:

integerBox.add(10) and integerBox.add(new Integer(10)) will result in an Integer being added to integerBox, but that's only because integerBox.add(10) transparently creates the Integer for you. Both ways may not necessarily create the Integer the same way, as one is explicitly being created with new Integer, whereas autoboxing will use Integer.valueOf(). I am going by the assumption the tutorial makes that integerBox is some type of collection (which takes objects, and not primitives).

But in this light:

int myInt = 10;
Integer myInteger = new Integer(10);

One is a primitive, the other is an object of type Integer.

like image 91
逆さま Avatar answered Jan 08 '23 06:01

逆さま