Initializing Elements in a Loop
Array objects have a single public variable, length that gives you the number of
elements in the array. The last index value, then, is always one less than the length.
For example, if the length of an array is 4, the index values are from 0 through 3.
Often, you'll see array elements initialized in a loop as follows:
Dog[] myDogs = new Dog[6]; // creates an array of 6
// Dog references
for(int x = 0; x < myDogs.length; x++) {
myDogs[x] = new Dog(); // assign a new Dog to the
// index position x
}
The length variable tells us how many elements the array holds, but it does not
tell us whether those elements have been initialized.
Array objects have a single public variable, length that gives you the number of
elements in the array. The last index value, then, is always one less than the length.
For example, if the length of an array is 4, the index values are from 0 through 3.
Often, you'll see array elements initialized in a loop as follows:
Dog[] myDogs = new Dog[6]; // creates an array of 6
// Dog references
for(int x = 0; x < myDogs.length; x++) {
myDogs[x] = new Dog(); // assign a new Dog to the
// index position x
}
The length variable tells us how many elements the array holds, but it does not
tell us whether those elements have been initialized.