我正在努力研究动态返回的方法
ArrayList<Player>
这是我所拥有的:
奇幻类
public class Fantasy {
Squad team;
ArrayList<Player> substitutes = team.getList(substitutes);
}
小队级别
public class Squad {
ArrayList<Player> substitutes;
// Some code adding stuff into the ArrayList
public ArrayList<Player> getList(String list) {
return ArrayList<Player> list; << PROBLEM
}
}
我想要一个方法getList()
,通过它我可以传递一个ArrayList的名称,它将检查是否存在同名的ArratList,如果存在,则将其返回为一个数组列表。
问题是我不知道如何检查是否有一个与我传递的 String list
名称相同的 ArrayList。
可能的解决方案:
Map<String, ArrayList<Player>> arrayLists = new HashMap<String, ArrayList<Player>>(){{
put("goalKeepers", goalKeepers);
put("defenders", defenders);
put("midFielders", midFielders);
put("strikers", strikers);
put("substitutes", substitutes);
}};
和
public ArrayList<Player> getList(String list) {
return arrayLists.get(list);
}
但是,当我打电话时:
ArrayList test = getList("substitute");
或者每当我使用 getList(); 时我收到以下错误:
Cannot make a static reference to the non-static method getList(String) from the type Squad
最佳答案
您不应该将替补列表存储在不同的实例变量中,而应该使用一个字段来存储球队名称到相应球员列表的映射:
public class Squad {
Map<String, List<Player>> substitutes = new HashMap<>();
// add the player lists into the map
/*
* Returns the list of players for the given team name,
* can be {@code null} if no player list has been stored
* with the team name.
*/
public List<Player> getList(String teamName) {
return substitutes.get(teamName);
}
}
关于java - 动态返回一个ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35676002/