How-To: Initialise arrays of objects in Java

You might think, like I did, that if you create an array of objects in Java then the constructor is automatically called on each object as part of the array creation process. But you’d be wrong.

Creating an array merely creates the object references – you have to instantiate each “inner” object in the array as a separate step if you want to be able to, ya know, do stuff… I think this is because in Java an array is an object – like, quite literally a single object that can be passed around like a single thing.

An example, perhaps?

Person Class

public class Person
{
	private int number = -1; // Each person gets a default number of -1 on creation
 
	// Default constructor
	public Person()
	{
		// The number property is left as -1 as per the default value specified above
	}
 
	// One parameter constructor which overwrites the default number value with a specified value
	public Person(int theNumber)
	{
		number = theNumber;
	}
 
	public void displayNumber()
	{
		System.out.println("My person number is: " + number);
	}
}

PersonTestDrive Class

public class PersonTestDrive
{
	final static public int MAX_PEOPLE = 3;
 
	public static void main(String[] args)
	{
		// Create an array of people. You're not creating any new People objects here - you're creating a new Array object
		Person[] people = new Person[MAX_PEOPLE];
 
		// *** INCORRECT : The Person objects in the people array don't exist yet! They're only references at this point! ***
		// for (Person tempPerson : people)
		// {
		// 	tempPerson.displayNumber(); // This doesn't give "-1" for each person, it gives a NullPointerException!
		// }
 
		// *** CORRECT : Instantiate each Person object in the array before accessing them! ***
		for (int loop = 0; loop < MAX_PEOPLE; loop++)
		{
			people[loop] = new Person(loop+1); // Create the Person object, setting the number property in this case
 
			people[loop].displayNumber();      // Now it'll output "My person number is: 1" etc. as expected
		}
	}
}

5 thoughts on “How-To: Initialise arrays of objects in Java”

  1. Good post

    Just knowing about the java.util.Arrays class could potentially save you massive amounts of time down the road.

    First sentence of Javadoc’s is…
    “This class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists.”

    1. Did not know about that class! (as I gather you gathered =P)

      Will check it out – thanks, mate!

      Also, liked your quote – but if you use <blockquote> you get a quote graphic (WOOOOooooo!)

      1. Basically, if you have a coding problem the chances are that somebody or some group will have written a library that solves it in a very re-usable and simple way.

        A great example of this is Apache Commons, but remember that this is only one example.

        That is why it’s really important to setup Maven Integration in your IDE. Getting a specific version of a specific jar is simply a right-click-and-select-from-list away. It’s like Synaptic for Java because it’ll get you all the jar’s that depend on it too.

  2. Thought that this may be of some use and is directly related to your code example, you could initialize arrays like this…

    private Integer[] myNumbers = {
        new Integer(17),
        new Integer(22)
    };

    But if you need to have a bunch of numbers initialized then logically speaking they could be properties, this will depend on your design. So I’d initialise them with a properties file instead of hard-code values within the class.

    Or retrieve them from a database

    Or you know, like… whateva

    Your mileage may vary (YMMV!)

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.