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.
finalwhen they are constant then this error would be flagged up by the compiler.