Mat
Mat

Reputation: 45

Java: Store int in Integer array

Can you store int values into a Integer array?

Given an array:

Integer[] array = new Integer[10];

Are the following two statements equivalent?

Integer x = new Integer(1);
array[0] = x;

int x = 1;
array[0] = x;

Upvotes: 1

Views: 3757

Answers (2)

hmir
hmir

Reputation: 1413

Once the values are inside the array itself, they are both values of type Integer. If you pass a primitive object to an instance of its wrapper class, then that primitive type is autoboxed, meaning its automatically converted to the type of its wrapper class.

Integer x = 4; //autoboxing: "4" is converted to "new Integer(4)"

Likewise, a wrapper class type can is unboxed when it is passed to a primitive type:

int x = new Integer(4); //unboxing: "new Integer(4)" is converted to primitive int 4

For your purposes, both examples your wrote will work.

Upvotes: 0

Puce
Puce

Reputation: 38152

They are not 100% equivalent. The following should be equivalent however:

Integer x = Integer.valueOf(1); 
array[0] = x;

int x = 1; 
array[0] = x;

Note that the int primitive gets autoboxed to the Integer wrapper class. So you're not storing an int primitive in the Integer array, but an Integer object.

You should hardly ever use the Integer constructor (which always creates a new object) but use one of its static factory methods or autoboxing (less code), which allow to cache instances (since they are immutable).

Upvotes: 2

Related Questions