Java Collection HashMap 问题

一个Room Class,一个Storey Class,一个House Class。。。
在Storey Class里面有HashMap<RoomReference, Room> roomMap;
在House Class里面有HashMap<Integer, Storey> storeyMap;

只有一个house,但是可以有多个storey,storey里面有多个room,
新建一个Room(1,1,1, 3, 4, 2,"RoomA")
1.1.1代表坐标,RoomA名称,3,4,2房间大小

如果此时storey里面有个Room[] getAllroom()方法,
return所有增加到这个storey的room,格式如下:
1,1,1:3,4,2:RoomA::
如果有多个room,return是一个array,如何做到?

另外,如果要在house class里面同样也有个Room[] getAllRoom(),
return这个house所有的房间,也就是说要每个storey里面的房间全部一起,也是返回一个array,如何做到?

//写了个例子,你依样画葫芦就行了
class Storey{
private String name;

public String getName() {
return name;
}

public Storey(String name) {
this.name = name;
}

public static void main(String[] args) {
HashMap<Integer, Storey> storeyMap=new HashMap<Integer, Storey>();
storeyMap.put(1, new Storey("one"));
storeyMap.put(2, new Storey("two"));
storeyMap.put(3, new Storey("three"));
storeyMap.put(4, new Storey("four"));
storeyMap.put(5, new Storey("five"));
Storey storeys[]=getAllStorey(storeyMap);
for (Storey storey : storeys) {
System.err.println(storey.getName());
}
}

public static Storey[] getAllStorey(HashMap<Integer, Storey> storeyMap){
List<Storey> list=new ArrayList<Storey>();
Set<Map.Entry<Integer, Storey>> storeySet=storeyMap.entrySet();
for (Map.Entry<Integer, Storey> entry : storeySet) {
list.add(entry.getValue());
}
Storey s[]=new Storey[list.size()];
return list.toArray(s);
}
}

参考资料:还有其他问题的话,给我发百度消息

温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-09-07
1 返回storey中的room数组:return roomMap.values().toArrary();
2 house中的room数组:
Collection<Storey> collection=storeyMap.values();

List<Room> list=new ArrayLiat<Room>();
for(Storey storey:collection)

list.addAll(storey.getRoomMap().values());

return list.toArray();
相似回答