java - 动态返回一个ArrayList

标签 java

我正在努力研究动态返回的方法

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/

相关文章:

java - 关于通知的线程

java - 如何获取 Firebase 中的最后一个节点?

java - Java读写文件和添加行号

java - HttpClient 卡住了,没有任何异常

java - 如何在Java中获取字段的注解

java - Java 中的 2D vector 旋转

java - 动态加载可能有异常的对象可以声明为final吗?

java - 使用 ClearNLP 语义角色标签器

java - 显示树中每片叶子的完整路径

java - 设计题: Java Class with single method ok?