Array declaration and assigning values to individual slots of Arrays

I asked this question earlier and got the things clear. However, I have some doubts, explaining below:

Let us assume the need is to have an array with 100 elements in this:

1) Declare array:

Integer[] intArr;

2) Allocate memory for 100 Integer elements and assign the reference to the variable

intArr = new Integer[100];

Now comes the real doubt.

Which one is correct way of assigning values to individual elements within the array:

Approach 1:

intArr[1] = 1;

Approach 2:

intArr[1] = new Integer(1);

My doubt is that we already have allocated memory for 100 elements and if we user Approach 2 , aren't we creating one more memory area and assigning them to the intArr1?

Does intArr[index] hold the reference's address or actual object can be placed in intArr[index].

Hope to get some insight to clear this doubt.

Jon Skeet
people
quotationmark

Those two lines are somewhat equivalent. The first uses auto-boxing. It's actually directly equivalent to:

intArr[1] = Integer.valueOf(1);

The difference is that this can reuse references to the same Integer object multiple times, whereas in your second approach you're creating a new Integer object. You can see the difference here:

intArr[1] = Integer.valueOf(1);
intArr[2] = Integer.valueOf(1);
System.out.println(intArr[1] == intArr[2]); // True, references to the same object

intArr[1] = new Integer(1);
intArr[2] = new Integer(1);
System.out.println(intArr[1] == intArr[2]); // False, references to the different objects

In all cases, the values of the array are references. They are never the objects themselves. When you allocate the array, that's creating enough space for 100 references, and those references are initially all null.

If you want an array that contains the integer data directly, just use an int[] instead of Integer[].

people

See more on this question at Stackoverflow