Would (1) int a; new Object[] {a} be the same as (2) new Object[] {new Integer(a)} ?
If I do the 1st one, will (new Object[]{a})[0] give me an Integer?
thank you
Would (1) int a; new Object[] {a} be the same as (2) new Object[]
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes and yes.
You can’t actually put an
intinto anObject[]. What you’re doing is making use of a feature of Java called autoboxing, wherein a primitive type likeintis automatically promoted to its corresponding wrapper class (Integerin 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 constructorInteger(int)as you do in (2) will always result in a newIntegerobject 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 newIntegerobject, or it may return a pre-existing cachedIntegerobject to save time and/or memory, depending on the value ofa. In particular, values between -128 and 127 are cached this way.In most cases this will not make a significant difference, since
Integerobjects are immutable. If you are creating a very large number ofIntegerobjects (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).