简体   繁体   English

检查地图中是否存在ArrayList

[英]Checking if an ArrayList exists in a map

My football team has 5 different teams and I am trying to make a program to keep a track of which players are registered with each team. 我的足球队有5个不同的球队,我正在尝试制作一个程序来跟踪每个球队注册的球员。 I want to be able to add a new player but first the program checks if that player is already registered. 我希望能够添加一个新玩家,但首先程序会检查该玩家是否已经注册。 I would also be able to add new teams in the future and again I would like to check if that team already exists. 我也可以在将来添加新的团队,我想再次检查该团队是否已经存在。

I have made a Map variable with 我用了一个Map变量

private Map<String, List<Player>> teamName;

then initialised this in the constructor 然后在构造函数中初始化它

teamName = new HashMap<>();

I then have a method to add new teams and new players, I want the method to check if the Club name already exists and then if it does exist, add the player name to that Club. 然后,我有一个方法来添加新的团队和新玩家,我希望方法检查俱乐部名称是否已经存在,然后如果它存在,则将玩家名称添加到该俱乐部。 if it doesn't exist then I want the program to add a new Club and then add that player to that club. 如果它不存在那么我希望程序添加一个新的俱乐部,然后将该球员添加到该俱乐部。

So far I have a method for adding a new player, 到目前为止,我有一种添加新玩家的方法,

public void newPlayer(String club, Player name) {
}

I am not sure how I now go about checking that an ArrayList exists for club and if it does add name to this list, if club does not exist then I want to make a new list and add name to it. 我不确定我现在如何检查club是否存在ArrayList,如果它确实为此列表添加了name ,如果club不存在,那么我想创建一个新列表并为其添加name

if I then run the program and write, 如果我然后运行程序并写,

Player jamesAtkinson = new Player();

newPlayer("first team", jamesAtkinson);

it would check if there is a List in the Map called 'first team' and then either add James Atikinson to it, or create a new List called first team and then add James Atkinson. 它会检查地图中是否有名为“第一队”的列表,然后将James Atikinson添加到其中,或者创建一个名为第一队的新列表,然后添加James Atkinson。

Is this even possible to do? 这甚至可能吗?

Although there are a few problems with code you've provided in the question. 虽然您在问题中提供的代码存在一些问题。 What you're looking for is the .containsKey function that hangs off of the Map interface. 您正在寻找的是挂起Map接口的.containsKey函数。

if (players.containsKey("first team") {
     // Do something
} else {
     List<Player> firstTeam = new ArrayList<>();
     firstTeam.add(jamesAtikson);
     players.put("first team", jamesAtikson);
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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