我需要创建一个 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>
类型的变量就会更加清晰。 :leftStands
和rightStands
,并有相应的方法: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/