Using the new (Integer) versus int

In my Java class, the professor uses something like:

integerBox.add(new Integer(10)); 

This is the same as simple:

 integerBox.add(10); 

? I was looking a little, but I can’t understand, anyway, and the professor was vague. The closest explanation I can find is the following:

int is a number; Integer is a pointer that can refer to an object containing a number.

+4
source share
3 answers

In principle, Java collection classes such as Vector , ArrayList , HashMap , etc., do not accept primitive types, such as int .

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

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

You would need to do this:

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

This is because 10 is just an int . Integer is a class that wraps an int primitive, and creating new Integer() means that you are actually making an object of type Integer . Before you start auto-boxing, you cannot mix Integer and int , as you are here.

So, takeaway:

integerBox.add(10) and integerBox.add(new Integer(10)) will add Integer to integerBox , but only because integerBox.add(10) transparently creates Integer for you. Both methods may not necessarily create an Integer in the same way as explicitly created using new Integer , while autoboxing will use Integer.valueOf() . I assume that the tutorial states that integerBox is some type of collection (which accepts objects, not primitives).

But in this light:

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

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

+4
source
 integerBox.add(10); 

equivalently

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

That way, it can return a cached instance of Integer.

Read the Java Specialist 191 for a different way to adjust the size of the autoboxing cache.

See also: cache options

+5
source

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

After the release of Java 5, however, something called autoboxing appeared. 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 names have a capital letter and a name referring to the primitive value that they represent).

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

0
source

All Articles