首页
学习
活动
专区
圈层
工具
发布

Java集合
EN

Stack Overflow用户
提问于 2013-04-23 15:43:11
回答 5查看 2.4K关注 0票数 0

我需要创建一个走廊类,它将在2 ArrayLists内设置站立对象,一个用于右边的看台,另一个用于左边的看台。

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

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

更重要的是,我的意图是使用如下方法访问这些ArrayLists:

TheHashTable“右”.add(StandObject);//在哈希表中的右侧立ArrayList中添加一个支架。

示例:

代码语言:javascript
复制
   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);
      }
}

这有可能吗?

EN

回答 5

Stack Overflow用户

发布于 2013-04-23 15:53:11

这是可能的,但我建议你不要这样做。如果您只有两个放置位置,那么简单地使用List<Stand>类型的两个变量:leftStandsrightStands,以及相应的方法:addLeftStand(Stand)addRightStand(Stand)等,就会更清晰、更简单、更安全。

如果你真的想走你的路,地图的键不应该是String。调用者不知道要传递哪个键给您的方法(字符串是无穷大的),即使他知道键是“右”和“左”,他也可以做一个错误,编译器不会注意到。您应该使用枚举,这将使代码具有自定义性和安全性:

代码语言:javascript
复制
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);
}
票数 3
EN

Stack Overflow用户

发布于 2013-04-23 15:50:27

如果您只有右和左,例如,可以创建2个数组列表。

代码语言:javascript
复制
private ArrayList<Stand> rightStands;
private ArrayList<Stand> leftStands;
票数 2
EN

Stack Overflow用户

发布于 2013-04-23 15:48:39

如果我清楚地理解你的问题,那么这就是你想要的:

代码语言:javascript
复制
public void addStand(Stand s){
 this.stand.get("Right").add(s);
}

但是更好的方法是使用地图而不是哈希表

代码语言:javascript
复制
public class Hallway {

 private Map< String, ArrayList<<Stand> > stands;
 private List<Stand> RightStands;
 private List<Stand> LeftStands;

 Hallway(){
    stands = new HashMap();
    RightStands = new ArrayList();
    LeftStands = new ArrayList();
    this.stands.put("Right", RightStands);
    this.stands.put("Left", LeftStands);
  }      

  public void addStand(Stand s){
     this.stands.get("Right").add(s);
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16173656

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档