Create an array of links

If I have a say A class, and I declare an array of 10 elements of this class, like

A [] arr=new A[10];

Then, 10 new A. objects are created and stored in the array.

However, I would like to do something in the lines A arr[10];where the array just contains references to null objects.

The reason I need this is because I only need an array to store the instances that I populate later in the code. Thus, the objects created above are still lost, and, as I understand it, creating an object is expensive.

So, is there a way to have an array of links that I can point to objects that I need later? Or is it impossible, and should I resort to use ArrayList?

+5
source share
3 answers

say A, 10 ,

A [] arr=new A[10];

10 A.

. , null. A, .

, , .

+12

A [] arr=new A[10];, , , null, .

A [] arr=new A[10]; A Class. arr , , arr[i].someMethod().

, :

A [] arr=new A[10];
arr[0] = new A();
arr[1] = new A();
:
:

:

  for(i=0; i<10; i++){
      arr[i] = new A();
  }

arr, , A. arr[i].someMethod() .

+4

JLS :

, (§4.12.5) , , , (§10, §15.10). , .

4.12.5.

(§4.3) null.

, :

If I have a class, say A, and I declare an array of 10 elements of this class, like, A [] arr = new A [10];
Then, 10 new objects are created and stored in the array.

It is not right. But what you want is right.

So, is there a way to have an array of links that I can point to objects that I need later?

+1
source

All Articles