Reputation: 631
If I have a class say A, and I declare an array of 10 elements of this class as,
A [] arr=new A[10];
Then 10 new objects of A are created and stored in the array.
However, i'd like to be able to do something on the lines of A arr[10];
, where the array just holds references to null objects.
The reason I need this is because I only need the array to hold instances I fill in later in the code. So the objects the above statement creates are lost anyway and as I understand object creation is expensive.
So, is there any way to just have an array of references that I can point to the objects I desire later? Or is this not possible and I should resort to using an ArrayList
?
Upvotes: 5
Views: 17835
Reputation: 531
This is a common OOP problem and can be solved using the Null Object
design pattern.
In order to not have to initialize n objects, you create a single static object of the same type for example:
public class A {
public static final A NULL = new A();
.
.
.
}
Now this object can act as your null reference by calling:
A[] arr = new A[10];
Arrays.fill(arr, A.NULL);
Which also conveniently leverages the use of .equals
and . hashCode
if you want to check for nulls.
Upvotes: 0
Reputation: 5798
if you do A [] arr=new A[10];
then no objects are created except your array, each field will be null
until you initialize it.
A [] arr=new A[10];
only create place to store reference of A
Class object. Although array arr
is created but its not referencing any object and you can't do like arr[i].someMethod()
.
To correct it, allocate object at individual memory in array do like this:
A [] arr=new A[10];
arr[0] = new A();
arr[1] = new A();
:
:
or in a loop like:
for(i=0; i<10; i++){
arr[i] = new A();
}
After there arr
that is an array of reference, refers to a valid A class object. And after this expression arr[i].someMethod()
will not cause an error.
Upvotes: 4
Reputation: 500367
If I have a class say
A
, and I declare an array of 10 elements of this class as,A [] arr=new A[10];
Then 10 new objects of A are created and stored in the array.
That's not correct. Here, an array of ten references gets created, and each reference gets set to null
. There are no instances of A
created by this code.
In other words, the code already does exactly what you'd like it to do.
Upvotes: 13