5

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?

3 Answers 3

13

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@akashasia Only one object is created, the array itself.
So I'm not wasting memory after all? Good to know. Looking at the new keyword I assumed the objects were being created. Thank you :)
4

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.

1 Comment

I added in your answer. you can revert back if you don't like.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.