Array of Objects Problem
The following example compiles, but doesn't run.I've tried looking for examples on the net and the Arrays chapter of Java: How to Program but I'm obviously still getting something wrong.
Any help would be appreciated.
// ArrayDemo.java
// Trying to figure out array of objects addressing
publicclass ArrayDemo{
publicclass Spread{
publicint percent;
publicint max;
publicint min;
}
publicclass Record{
public Spread range[] =new Spread[5];
}
publicstaticvoid main( String[] args ){
Record collection[] =new Record[5];
collection[3].range[2].max = 3;
}
}
When allocate an array, for example:
Record collection[] = new Record[5];
the result is an array of nulls, not an array of references to newly
created Record objects. You must loop and create the objects,
assigning references to them into the array.
public class ArrayDemo {
public static class Spread {
public int percent;
public int max;
public int min;
}
public static class Record {
public Spread range[] = new Spread[5];
public Record() {
for(int i=0; i < range.length; ++i) {
range[i] = new Spread();
}
}
}
public static void main( String[] args ) {
Record collection[] = new Record[5];
for(int i=0; i < collection.length; ++i) {
collection[i] = new Record();
}
collection[3].range[2].max = 3;
}
}
The statement:
Record collection[] = new Record[5];
creates an array of type Record with each position initially set to null--it doesn't create the Records themselves. Before you can reference an actual Record, you must initialize it:
collection[3] = new Record();
collection[3].range[2].max = 3;