我需要能够从另一个HashMap中的HashMap获取值。我对HashMaps并不是那么熟悉所以我自己也无法解决这个问题。 代码:
import java.util.HashMap;
public class testfile2 {
public static void main(String args[]){
HashMap<String, HashMap<String, String>> rooms = new HashMap<String, HashMap<String, String>>();
HashMap<String,String> roomA = new HashMap<String,String>();
roomA.put("desc1","You are in a dark room made out of wood. Some light shines through a window to the South.From this light you can make out a door to the East");
roomA.put("desc2", "You are in a dark room made out of wood. Some light shines through a broken window to the South.From this light you can make out a door to the East. There is a tunnel leading outwards from the window.");
rooms.put("roomA", roomA);
HashMap<String, String> roomB = new HashMap<String, String>();
roomB.put("desc1", "You are in a dark wooden room. There is nothing here but a doorway leading to the West.");
roomB.put("desc2", "You are in a dark wooden room. There is a doorway that leads to the West. There is also an axe you can take on the ground.");
rooms.put("roomB", roomB);
HashMap<String, String> roomC = new HashMap<String, String>();
roomC.put("desc1", "You are in a completely white rectangular room. There is a rectangular hole in the wall to the North.");
rooms.put("roomC", roomC);
System.out.print(rooms.get("roomA"));
}
}
我需要能够打电话给#34; desc1&#34;来自字符串&#34; roomA&#34;那是在HashMap房间里。
进一步澄清:System.out.print(rooms.get(&#34; roomA&#34; .get(&#34; desc1&#34;)); 上面的印刷声明就像我需要的东西。我知道我不能使用String&#34; roomA&#34;使用.get,但如果有任何办法可以做到这一点,我真的很感激一些帮助。
答案 0 :(得分:1)
rooms.get("roomA").get("desc1")
是简短的回答。由于你是HashMaps的新手,让我们澄清一下。
rooms
是HashMap
,它将字符串映射到HashMap<String, String>
。因此,您在房间呼叫的每个.get(...)
都有HashMap<String, String>
的返回类型。在.get(...)
的任何内容上调用HashMap<String, String>
都会返回String
类型的值,这就是您的目标。
因此
rooms.get("roomA")
返回HashMap<String,String>
和
rooms.get("roomA").get("desc1")
返回String。
另一种思考方式是将其分为两个陈述:
HashMap<String, String> myRoom = rooms.get("roomA");
String desc = myRoom.get("desc1");
然后可以很容易地将其压缩到rooms.get("roomA").get("desc1")
。
答案 1 :(得分:0)
rooms.get("roomA").get("desc1")
应该有用。
当然最好检查是否存在,以避免潜在的NullPointerException
:
if (rooms.get("roomA") != null) {
System.out.println(rooms.get("roomA").get("desc1"));
}