r3dux.org

A number-pimping side project from the valleys in *NEW* upside-down flavour.

  • Home
  • ABOUT
  • OLD SITE
  • SEARCH
  • FEEDBACK

How-To: Initialise arrays of objects in Java

r3dux | October 7, 2011

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
		}
	}
}

Related posts:

  1. Java enhanced for-loop FTW
  2. How-To: Get human-friendly dates in Java using the Calendar class
  3. How to: Create and insert SQL DATE or DATETIME objects using PHP
  4. ActionScript 3.0 Particle Systems #4: Bubbles
  5. ActionScript 3.0 Particle Systems #2: Snow Effect
Categories
Coding, How-To
Tags
Array, Constructor, Exception, Initialise, Java
Comments rss
Comments rss
Trackback
Trackback
Print This Post Print This Post

« Gillian Welch – Everything is Free Me vs. Software vs. The World, or How to transition from Alpha to Beta »

5 Responses to “How-To: Initialise arrays of objects in Java”

  1. shetboy says:
    October 7, 2011 at 4:01 pm

    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.”

    Reply
    • r3dux says:
      October 7, 2011 at 7:24 pm

      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!)

      Reply
      • shetboy says:
        October 7, 2011 at 9:47 pm

        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.

        Reply
  2. shetboy says:
    October 20, 2011 at 11:30 pm

    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!)

    Reply
    • r3dux says:
      October 21, 2011 at 10:32 am

      Hmm, never heard of a properties file – that seems pretty good, actually! Ta! =D

      Reply

Leave a Reply

Click here to cancel reply.

Translate

Categories

Archives

Tags

3D ActionScript ActionScript 3.0 Adobe AI Ballarat Bash C++ Class Convert CS4 Effect Error Film Flash FPS GLFW Glitch GLSL Hack How-To install Java Kinect Linux Live Mash-Up Microsoft Motion mount OpenGL Particle Problem PS3 Remix Retro script Slides Sound Ubuntu Video VirtualBox Wii Windows XBox

Gamercard

OpenR3dux

Misc.

Flattr this

RSS Feed

r3dux twitter feed



“Put the needle to the record not the needle to the vein.”

 - Dilated Peoples

rss Comments rss valid xhtml 1.1 design by jide powered by Wordpress get firefox