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

PersonTestDrive Class

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…

    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.