Search code examples
javarr

Java ArrayList in ArrayList


I have a question about an ArrayList inside an Arraylist. It's about multiple worlds with multiple spawns. I want to check every world one by one and save all the spawns of that world in an ArrayList. At the end I have an ArrayList with on every position (every position is a world) another Arraylist containing the spawns of that world.

How can I do this if I don't know how many spawns or worlds there are going to be? I thought of this:

Looking to just one world:

public ArrayList<Location> Spawnpoints = new ArrayList<Location>(); 
//ArrayList containing all the spawns of this world).

Looking to every single spawn in the world

 Spawnpoints.add(new Location(spawnX , spawnY , spawnZ)); 
//Adding every spawn to the ArrayList spawnpoints.

So after I looked at a world I have filled the ArrayList spawnpoints with locations. Now I want to add the ArrayList spawnpoints to a new ArrayList worlds. After that I will repeat the code above for the next world, untill I have had all the worlds.

EDIT. I think it's working. I have troubles with getting the size of the list when I only have the name.

So let's say I did this: allSpawnpoints.put("yourWorld",Spawnpoints); Now I want to get the size of the Spawnpoints list for the string yourWorld. Any idea how I can do this?

I tried: int number = allSpawnpoints.get("yourWorld").size(); it looks like that isn't working.

I hope someone can help me! Thanks for reading. Regards.


Solution

  • Instead of an ArrayList or World objects try using a Map of World to List of Location. Something like this:

    Map<World,List<Location>> allSpawnpoints = new HashMap<World,List<Location>>();
    

    Then, after you have created your list of spawnpoints for a World put it into your Map like this:

    allSpawnpoints.put(yourWorld,Spawnpoints);
    

    ... and then move onto the next World.

    I would also suggest renaming Spawnpoints as spawnPoints.