PDA

View Full Version : Adding to an ArrayList within an ArrayList


webguy08
04-11-2009, 06:09 PM
Hi all,
I have an ArrayList of type ArrayList (ArrayList<ArrayList> arrayOfAnimalArrays) which holds ArrayLists of type Animal (ArrayList<Animal> arrayOfAnimals). I also have an ArrayList of type Animal which holds all of the animals available (ArrayList<Animal> animals).

For clarity of what I'm trying to achieve, imagine this as the tale of Noah's Ark. The 'animals' ArrayList holds all of the animals Noah has to put in his Ark. The 'arrayOfAnimalArrays' ArrayList are the rooms on the Ark to hold the different animals in. The 'arrayOfAnimals' ArrayList are the animals to put in those rooms. I need to add the animals to the rooms in the Ark :p

Now back in context, I need to add an Animal from 'animals' to 'arrayOfAnimals'. I have tried the following code:
arrayOfAnimalArrays.add(0, animal.get(0));
However this does not work because of animal.get(0) where it states that it "cannot find symbol - method add(int, Animal)".
Note: I am using 0 as an example, I plan to actually use a variable (say 'i') to hold a changing value.
I guess it seems logical for it to complain because arrayOfAnimalArrays holds ArrayLists, not Animals. However, at the index 0 in arrayOfAnimalArrays there is an ArrayList of Animals, so I thought it should be able to add the animal it gets from 'animals' into it :confused:

Any ideas?

webguy08
04-12-2009, 01:50 PM
Anyone? :(

Fou-Lu
04-12-2009, 08:40 PM
Sorry mate, lots of information there.
First, lets look at the add method that its whining about. The animal.get is acutally succeeding, according to the error, it doesn't have an overload for add(int, Animal).
This is correct though, from the sounds of the problem description. It sounds like you should be adding on you're arrayOfAnimals.add(animals.get(0));, not on the arrayOfAnimalsArray.add(animals.get(0));
I make this assumption since the arrayOfAnimalsArray is the one throwing the compilation error. It wants an arrayList, not an animal, so you would want to add the 'Animal' to the 'arrayOfAnimals', and add his 'arrayOfAnimals' to the 'arrayOfAnimalsArray'.

To do what you're mentioning at the bottom (with the arrayList, which you do notice), you'd need to first get the arraylist from the list, then add. Something like this:

arrayOfAnimalsArray.get(i).add(j, animals.get(k));

Annoying eh? I'd go with the addition of the animal to the arrayOfAnimals, then just push that onto the arrayOfAnimals array.

Depending on what you do of course, perhaps the arrayList is not the right structure you need. From the 'story' of the ark, I'd suggest that a Matrix may be more along what you're looking to do, so you can usher different animal collections (you're arrayOfAnimals) into different matrix blocks (like the rooms). Does that make sense? Does that help you at all?

webguy08
04-12-2009, 10:27 PM
Thank you so much! :thumbsup: Another trick I have learned from this forums :D