Erik Price
Posts: 39
Nickname: erikprice
Registered: Mar, 2003
|
|
Re: Create an array of objects
|
Posted: May 2, 2003 8:05 AM
|
|
Hi Niffin,
The problem is here:
Train trains[]; //i think this makes an array of train objects.
trains = new Train[10]; //i hope this intialises the array.
This doesn't do what you think it does. The first line declares an array of Train objects named "trains". That part is fine, but it doesn't actually make the array. It just says "whenever I use the reference 'trains' I'm referring to an array of Train objects".
The second line is where the array is actually created and initialized. You're basically telling the compiler to allocate the memory required to store a 10-element array of Train objects. But you haven't actually put any Train objects into the array. (Each element of "trains" is still null.)
What you need to do now is actually add instances of Train objects to the array by directly assigning them to the individual elements. Here is one, kind of long, way to do it:
trains[0] = new Train(5, 8); trains[1] = new Train(4, 32); trains[2] = new Train(88, 222); ...
Another way to do it is to loop through the array and create a new Train object for each element:
for (int i = 0; i < trains.length; i++) { trains[i] = new Train(5, 654); }
The lesson here is that when you create an array of non-primitives (in other words, an array of objects), the array is initialized such that each element is null. You still have to manually add instances to the array's elements somehow.
|
|