java - HashMap内部Hashmap打印涉及字符串?

标签 java string hashmap

我需要能够从另一个 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 新手,让我们稍微澄清一下。

roomsHashMap将字符串映射到 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/

相关文章:

java - 通过 Swing GUI 控制 Selenium

java - 使用静态函数/变量相对于类/对象有什么好处吗?

java - 在具有嵌入式 Tomcat 的 jar 上提供额外的类路径

python - 试图计算字符串中的单词

python - 如何根据Python中的字典替换大字符串的子字符串?

c++ - std::string 附加线程安全天真的解决方案?

java - 针对 HashMap 中的所有值查找值

java - 在android中自定义图片库

java - 如何使用一组中的键和另一组中的值填充 HashMap

java - 调用 hashmap.get(object) 时在 HashMap 对象中获取 null 值