java - Intellij idea Hashmaps打印到控制台

标签 java intellij-idea hashmap console-application

我正在尝试将 2 个 HashMap 的数据打印到控制台,但我注意到那里只描绘了一个。这是一个代码示例:

public class HashMapsmathces {
    public static void main(String[] args) throws Exception {

    Map<String, Object> hm1 = new HashMap<>();

    hm1.put("id", 1);
    hm1.put("sku","qazwsx");
    hm1.put("price", 11);

    printMaps(hm1);

    Map<String, Object> hm2 = new HashMap<>();

    hm1.put("id", 2);
    hm1.put("sku","qazwsx");
    hm1.put("price", 13);

    printMaps(hm2);
}

public static void printMaps(Map<String, Object> map)
{

    for (Map.Entry<String, Object> pair : map.entrySet())
    {
        String key = pair.getKey();
        String value = pair.getValue().toString();
        System.out.println(key + " : " + value);
    }
    }
}

因此,当我按“运行”时,只有 hm1 会被推送到控制台。我不太清楚为什么。

这里还有截图 enter image description here

谢谢。

最佳答案

那是因为 hm2 为空,您在声明 hm2 映射后将值重新分配给 hm1。

public class HashMapsmathces {
    public static void main(String[] args) throws Exception {

    Map<String, Object> hm1 = new HashMap<>();

    hm1.put("id", 1);
    hm1.put("sku","qazwsx");
    hm1.put("price", 11);

    printMaps(hm1);

    Map<String, Object> hm2 = new HashMap<>();

    hm2.put("id", 2);
    hm2.put("sku","qazwsx");
    hm2.put("price", 13);

    printMaps(hm2);
}

public static void printMaps(Map<String, Object> map)
{
    //напишите тут ваш код
    for (Map.Entry<String, Object> pair : map.entrySet())
    {
        String key = pair.getKey();
        String value = pair.getValue().toString();
        System.out.println(key + " : " + value);
    }
    }
}

关于java - Intellij idea Hashmaps打印到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42606664/

相关文章:

c# - 如何使用 Quartz 调度程序维护作业历史记录

java - 如何从 Java 发送短信?

java - 读取文件时未报告的异常 FileNotFoundException

java - 确定哪个条件导致 if 语句执行

java - intellij 拒绝连接到 http ://127. 0.0.1:8888

java - 存储 HashMap 值与引用值的效率

java - Hashmap 的空索引里面有什么?

java - 为什么我在 maven 中添加的依赖项会出现模块丢失错误,并且我需要解决它?

java - 我必须使大部分变量成为最终变量有意义吗?

java - 我如何评估哈希表的实现? (引用HashMap)