HashMap内部HashMap打印涉及字符串



我需要能够从另一个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"));
    }
}

我需要能够调用"desc1"从字符串"roomA"是在HashMap房间。

进一步说明:System.out.print(rooms.get("roomA".get("desc1"));我需要的就是上面的print语句。我知道我不能使用字符串"roomA"与。get,但如果有任何方法我可以做到这一点,我真的很感激一些帮助。

rooms.get("roomA").get("desc1")是简短的答案。因为您是HashMaps的新手,所以让我们稍微澄清一下。

rooms是将字符串映射到HashMap<String, String>HashMap。所以你在房间上调用的每个.get(...)都有一个返回类型HashMap<String, String>。在HashMap<String, String>上调用.get(...)将返回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")

rooms.get("roomA").get("desc1")应该可以。

当然最好检查是否存在,以避免潜在的NullPointerException:

if (rooms.get("roomA") != null) {
    System.out.println(rooms.get("roomA").get("desc1"));
}

最新更新