Reputation: 13
I have the problem with the following method. It is supposed to create an array, fill it up with objects, and return the filled array. However, for a reason unknown to me, the returned array is full of null values.
public Rodent[] getRodents(int amount) {
Random rng = new Random();
Rodent[] rodentArray = new Rodent[amount];
for (Rodent r : rodentArray) {
switch (rng.nextInt(3)) {
case 0:
r = new Mouse(); // Subclass of Rodent
break;
case 1:
r = new Gebril(); // Subclass of Rodent
break;
case 2:
r = new Hamster(); // Subclass of Rodent
break;
default:
r = new Rodent(); // For safety
}
System.out.println(r.getName()); // Test command inside the loop. Prints the name of all object correctly.
}
for (Rodent r : rodentArray) { // Test loop outside of previous loop.
System.out.println(r.getName()); // Throws null pointer exception.
}
return rodentArray; // Returns null filled array
}
EDIT:
Found my answer. Thanks. Now i need to stop thinking about the enhanced for loop like a pointer.
Upvotes: 1
Views: 72
Reputation: 288
You are never putting newly created rodent object into array. Here is the correct code -
public Rodent[] getRodents(int amount) {
Random rng = new Random();
Rodent[] rodentArray = new Rodent[amount];
for(int count = 0; count < rodentArray.length; count++) {
Rodent r;
switch (rng.nextInt(3)) {
case 0:
r = new Mouse(); // Subclass of Rodent
break;
case 1:
r = new Gebril(); // Subclass of Rodent
break;
case 2:
r = new Hamster(); // Subclass of Rodent
break;
default:
r = new Rodent(); // For safety
}
rodentArray[count] = r;
System.out.println(r.getName()); // Test command inside the loop. Prints the name of all object correctly.
}
for (Rodent r : rodentArray) { // Test loop outside of previous loop.
System.out.println(r.getName()); // Throws null pointer exception.
}
return rodentArray; // Returns null filled array
}
Upvotes: 0
Reputation: 328863
r
is a local variable in your loop that does not exist outside a given iteration. Your code is equivalent to the code below where it is maybe easier to see that the r
is discarded at the end of each iteration:
for (int i = 0; i < rodentArray.length; i++) {
Rodent r = rodentArray[i];
//your switch here
}
So in your case you should probably use a standard for loop and fill the array with rodentArray[i] = new Mouse();
or with other animals as appropriate.
Upvotes: 4