简体   繁体   中英

Java Arraylist listing all elements

I have two array lists, one for teams and one for players. The arraylist for players is in the teams class and I've successfully managed to get it so that each team can have players added to it.

But what I'm wondering is what is the best way to iterate through the collection to show all players regardless of the teams they are associated too? Is that even possible?

您可以使用所有玩家创建一个新列表:

List<Player> allp = new ArrayList<Player>();

for(Team t : teams) allp.addAll(t.getPlayers());

You would have to create another structure that contained references to all the players. For example, you could have another collection for all players, and just be sure to add new Players to that collection whenever they get created. A Set has desirable semantics such as not allowing dupes, so that might make sense for you.

Or just loop thru all teams, looping thru all players....

There is no way to say loop thru all Players regardless of which collection they are in, within the collections framework.

Maybe you should be using a Map<String,List<String>> instead, where key is the name of the team and the value is a list of the players in that team. That way you can get all the values (using map.values() ) of this map and iterate over them to get a list of all players regardless of the team.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM