Java集合

标签 java collections arraylist hashtable

我需要创建一个 Hallway 类,其中包含 2 个 ArrayList 的 Stand 对象,一个用于右侧的看台,另一个用于左侧的看台。

我的目的是将这些ArrayLists放入此类的另一个集合中。

我不知道是否应该使用 Hashtable、Map 等。

更重要的是,我的目的是使用以下方法访问这些 ArrayList:

TheHashTable["Right"].add(standObject); // Add a Stand to the Right Stands ArrayList which is inside a Hashtable.

示例:

   public class Hallway {       

      private Hashtable< String, ArrayList<<Stand> > stands;

      Hallway(){
         // Create 2 ArrayList<Stand>)
         this.stands.put("Right", RightStands);
         this.stands.put("Left", LeftStands);
      }      

      public void addStand(Stand s){
         this.stands["Right"].add(s);
      }
}

这可能吗?

最佳答案

这是可能的,但我建议不要这样做。如果您只有两个立场位置,那么只需拥有两个 List<Stand> 类型的变量就会更加清晰。 :leftStandsrightStands ,并有相应的方法:addLeftStand(Stand) , addRightStand(Stand)等等。代码会更清晰、更简单、更安全。

如果你真的想走自己的路, map 的键不应该是字符串。调用者不知道将哪个键传递给您的方法(有无限的字符串),即使他知道键是“右”和“左”,他也可能会犯一个拼写错误,而该错误不会被编译器。您应该使用枚举,这将使代码 self 记录并且更安全:

public enum Location {
    LEFT, RIGHT
}

private Map<Location, List<Stand>> stands = new HashMap<Location, List<Stand>>();

public Hallway() {
    for (Location location : Location.values()) {
        stands.put(location, new ArrayList<Stand>());
    }
}

public void addStand(Location location, Stand stand) {
    stands.get(location).add(stand);
}

关于Java集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16173656/

相关文章:

Java ArrayList for-loop lcv 被认为是一个对象,而不是一个 int

java - Eclipse JSP项目错误: org. apache.catalina.core.ApplicationContext日志严重:操作:null

java - 为什么会发生 JsonParseException ?

java - RSS 源的大小

java - 内部对象更改时 HashSet 的哈希解决方法

c# - 从方法返回 List<T> 的性能是否与返回 Collection<T> 不同?

java - 有没有办法清除 arraylist 但不尊重内存引用?

java - 为什么java不支持指针?

c# - 适用于 .NET 的 Microsoft 集合

java - 通过指定索引从 ArrayList 中检索元素