Reputation: 385
I'm doing the last challenge on this forum post called 'graduation' except in Java instead: http://www.cplusplus.com/forum/articles/12974/
I've basically stumbled across a problem where if I have an arrayList of bunny objects that spawns new offspring based on the amount of males and females, I need to give each new offspring a dynamic name for the list or the compiler goes mental and throws a ConcurrentModifierException (which I'm assuming is because it's trying to go through multiple objects that have the same variable name).
The only way I can think of is by making a Bunny object array like saying:
bunnyList.add(bunny[i + 1])
Where i is the kind of 'global' id for all the bunnies. But the problem is that if I add it to the list it's illegal. To be honest, I'm not sure why either since I set the array list to be of type bunny array rather than just plain old bunny.
public class Bunnies {
private static ArrayList<Bunny[]> bunnyList = new ArrayList<Bunny[]>();
private static Bunny[] bunny = new Bunny[500]; //gives it a kind of id
private static int i = 0; //global bunny counter
Bunnies(){
//init the game list.
initBunnyGameList();
}
private void initBunnyGameList(){
for (int i = 0; i < 5; i++){
bunny[i] = new Bunny();
bunnyList.add(bunny[i]); //ILLEGAL :(!
}
}
}
Also doing it this way seems like a massive waste of memory to create an array space for 500 possible bunny objects only to ever use ONE space as an identifier. But I can't seem to think of a way to name each variable dynamically in any other way. Really, what I need is a way to generate variables with a number on the end when I make a bunny so they're all individual no matter what.
Any suggestions hombres?
Upvotes: 2
Views: 1398
Reputation: 93842
bunny[i]
is actually a Bunny
object, not an array
of Bunny
objects.
private static ArrayList<Bunny[]> bunnyList = new ArrayList<Bunny[]>();
should be
private static ArrayList<Bunny> bunnyList = new ArrayList<Bunny>();
Upvotes: 2