简体   繁体   中英

using new(Integer) versus an int

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, 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 .

integerBox.add(10);

is equivalent to

integerBox.add(Integer.valueOf(10));

So it may return the cached Integer instance.

Read Java Specialist 191 for various way of setting autoboxing cache size.

See also: cache options

In this case, yes. I'm assuming that integerBox is a collection of objects - you can only store objects within integerBox. This means that you cannot have a primitive value, such as an int, within the collection.

After Java 5 was released, however, there came about something called autoboxing. Autoboxing is the process of automatically converting a primitive value to an object. This is done through one of the wrapper classes - Integer, Double, Character, etc (all named with a capital letter and a name pertaining to the primitive value that they represent).

When you added int 10 to the collection(ArrayList, most likely), the Java VIrtual Machine transformed it into an object of type Integer behind the scenes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM