2

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?

1 Answer 1

2

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>(); 
Sign up to request clarification or add additional context in comments.

2 Comments

Also, for the OP: It's a good practice to type your variables as interface types unless you REALLY need functionality specific to the implementation type: private static List<Bunny> bunnyList = new ArrayList<Bunny>();
Haha that was unexpectedly simple but it's worked! I can see where my confusion was too. I guess I was just using ArrayList because it's what I know, I've only really just got into this more advanced OO stuff, but I can see where you're coming from, I'll make sure to look in the future at what I actually use in the API and scale down or up based on what I find x

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.