我需要能够从另一个 HashMap 内的 HashMap 获取值。我对 HashMap 不太熟悉,所以我自己无法真正弄清楚这一点。 代码:
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"));
}
}
我需要能够从 HashMap 房间中的字符串“roomA”调用“desc1”。
进一步澄清:System.out.print(rooms.get("roomA".get("desc1")); 我需要的是像上面的打印声明这样的东西。我知道我不能将字符串“roomA”与 .get 一起使用,但如果有任何方法可以做到这一点,我将非常感谢一些帮助。
最佳答案
rooms.get("roomA").get("desc1")
是简短的答案。由于您是 HashMap 新手,让我们稍微澄清一下。
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")
返回字符串。
另一种思考方式是将其分为两个语句:
HashMap<String, String> myRoom = rooms.get("roomA");
String desc = myRoom.get("desc1");
然后可以轻松地将其压缩为 rooms.get("roomA").get("desc1")
.
关于java - HashMap内部Hashmap打印涉及字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25235004/