Can I get Integer or int after putting int into array of objects?

Will (1) int a; new Object[] {a}

be the same as (2) new Object[] {new Integer(a)}

? If I do the first, will you (new Object[]{a})[0]

give me Integer

? thanks

+2


a source to share


2 answers


Yes and yes.

You cannot put int

in Object[]

. What you are doing is using a Java feature called autoboxing, where the primitive type of the type is int

automatically promoted to the appropriate wrapper class ( Integer

in this case) or vice versa as needed.

You can read more about this here .

Edit:



As Jesper points out in the comment below, the answer to your first question is not really "yes," but "it depends on meaning a

." The call to the constructor Integer(int)

, as in (2), will always result in the creation of a new object Integer

and its input into the array.

In (1), however, the autoboxing process will not use this constructor; it will essentially call Integer.valueOf(a)

. This can create a new object Integer

or it can return an already existing cached object Integer

to save time and / or memory depending on the value a

. In particular, values ​​between -128 and 127 are cached.

In most cases, this will not make a significant difference, since objects are Integer

immutable. If you create a very large number of objects Integer

(well over 256 of them) and most are between -128 and 127, your example (1) is likely to be faster and uses less memory than (2).

+9


a source


What's going on under the hood is the Java compiler adds code like Integer.valueOf (a) to convert an int value to Object.



0


a source







All Articles