Kgrover
Kgrover

Reputation: 2116

Why doesn't Java initialize Array Objects?

If one runs the following code in java:

public class Testing {

    public static void main(String[] args) {
        TestObject[] array = new TestObject[4];
        //array[0] = new TestObject();
        System.out.println(Arrays.asList(array));
    }
}

class TestObject {
    String aString;

    public TestObject() {
        aString = "This has been initialized.";
    }
}

It will print (null, null, null, null), and if array[0] = new TestObject(); is uncommented, then the first object will have a memory address (and not be null). I'm just confused to as to why Java wouldn't automatically call the constructor for each Object in an array when the array is first initialized properly. What are the advantages of the way it works right now? Is it a space issue (as in it would be too costly to do so)?

Maybe I've just overlooked something silly or I'm simply mistaken. This is not directly related to a problem I'm having, so if it's the wrong forum I apologize.

Upvotes: 3

Views: 3117

Answers (2)

Mirko
Mirko

Reputation: 1552

With new TestObject[4] you create an array, wich can hold 4 references to TestObject. So understand the difference between TestObject[] and TestObject:

TestObject[] is a reference store for TestObject - objects. If you create a List<TestObject> you'll have to fill up the list with references too.

Upvotes: 0

Paul Tomblin
Paul Tomblin

Reputation: 182782

What happens if you want to fill up your array with real objects that are subclasses of TestObject, or which are constructed with non-default constructors? In the real world, you rarely want an array with a bunch of identical objects.

Upvotes: 6

Related Questions