我需要创建一个走廊类,它将在2 ArrayLists内设置站立对象,一个用于右边的看台,另一个用于左边的看台。
我的目的是将这些ArrayLists放在这个类的另一个集合中。
我不知道是否应该使用Hashtable、Map等。
更重要的是,我的意图是使用如下方法访问这些ArrayLists:
TheHashTable“右”.add(StandObject);//在哈希表中的右侧立ArrayList中添加一个支架。
示例:
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);
}
}这有可能吗?
发布于 2013-04-23 15:53:11
这是可能的,但我建议你不要这样做。如果您只有两个放置位置,那么简单地使用List<Stand>类型的两个变量:leftStands和rightStands,以及相应的方法:addLeftStand(Stand)、addRightStand(Stand)等,就会更清晰、更简单、更安全。
如果你真的想走你的路,地图的键不应该是String。调用者不知道要传递哪个键给您的方法(字符串是无穷大的),即使他知道键是“右”和“左”,他也可以做一个错误,编译器不会注意到。您应该使用枚举,这将使代码具有自定义性和安全性:
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);
}发布于 2013-04-23 15:50:27
如果您只有右和左,例如,可以创建2个数组列表。
private ArrayList<Stand> rightStands;
private ArrayList<Stand> leftStands;发布于 2013-04-23 15:48:39
如果我清楚地理解你的问题,那么这就是你想要的:
public void addStand(Stand s){
this.stand.get("Right").add(s);
}但是更好的方法是使用地图而不是哈希表。
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);
}
}https://stackoverflow.com/questions/16173656
复制相似问题