Arrays of Objects



The above program is similar to others you have done to this point with a few major exceptions: there is an array used – and more than that it is an array of objects.  Further, you’ll note that it doesn’t just have one main class plus a class for making certain objects, but it also has a class that specializes in a certain functionality, which in this case is basically searching.

The biggest consideration with an array of objects is that the objects themselves must be instantiated before they can be used.  It is not enough to just instantiate the array, you also have to instantiate the objects.  And this is quite often forgotten, and results in a Null Pointer Exception.  Here is an example of how that error could happen:

VideoGame[] videoGameArray = new VideoGame[10]; 

Error:  Null Pointer Exception.

To reiterate, yes, the videoGameArray array has been instantiated, but an array of objects is an array of references, and object references are instantiated to null.  So after the first line above there is an array called videoGameArray, which is three contiguous 32-bit areas of memory, all three storing null, for the time being.  Therefore, when trying to access the getRating() method of element number 1 of the array, well, it itself has not yet been created, so there’s nothing to get, thus the error.

To prevent this error from happening, you just have to remember to instantiate each of the object elements of an array of objects – even if it’s just to some default values. The following code does that nicely in this case:

VideoGame[] videoGameArray = new VideoGame[10]; 
for(int i = 0; i < 10; i++){ videoGameArray[i] = new VideoGame("aasdasd", 0); }

By the way, here’s an alternative way it could have been done, all in one line, using the other approach to making arrays, which you may remember:

VideoGames[] videoGamesArray = { new VideoGame(“”, 0), new VideoGame(“”, 0), new VideoGame(“”, 0) };

Recall that with this way of making arrays we don’t have to put anywhere the number of elements in the array, since it’s obvious by the number of things separated by commas between the braces.

The following page has a diagram that shows what is going on at the memory level with all of this.

(And you'll not,e from a "deep/full understanding" perspective, that the array is the "container", rather than what is contained. Similarly to the fact that an object is the reference to data, not the data itself. So in the diagram below, the array videoGameArray actually is the reference to the three pieces of data, or put another way, it is the container.)