开发者

Do I get an Integer or int after putting an int into an object array?

开发者 https://www.devze.com 2022-12-31 11:16 出处:网络
Would (1) int a; new Object[] {a} be the same as (2) new Object[] {new Integer(a)} ? If I do the 1st 开发者_JS百科one, will (new Object[]{a})[0] give me an Integer?

Would (1) int a; new Object[] {a} be the same as (2) new Object[] {new Integer(a)} ? If I do the 1st 开发者_JS百科one, will (new Object[]{a})[0] give me an Integer? thank you


Yes and yes.

You can't actually put an int into an Object[]. What you're doing is making use of a feature of Java called autoboxing, wherein a primitive type like int is automatically promoted to its corresponding wrapper class (Integer in this case) or vice versa when necessary.

You can read more about this here.

Edit:

As Jesper points out in the comment below, the answer to your first question is actually not "yes" but "it depends on the value of a". Calling the constructor Integer(int) as you do in (2) will always result in a new Integer object being created and put into the array.

In (1), however, the autoboxing process will not use this constructor; it will essentially call Integer.valueOf(a). This may create a new Integer object, or it may return a pre-existing cached Integer object to save time and/or memory, depending on the value of a. In particular, values between -128 and 127 are cached this way.

In most cases this will not make a significant difference, since Integer objects are immutable. If you are creating a very large number of Integer objects (significantly more than 256 of them) and most of them are between -128 and 127, your example (1) will be probably be faster and use less memory than (2).


What happens under the hood is Java compiler adds code like Integer.valueOf(a) in order to convert your int value into an Object.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号