首页 > 解决方案 > HashMap获取键值的意外字符串

问题描述

我有这段代码:

private static void addItem(String[] commandParsed, Set<Item> inventory, Map<String, Map<String, Item>> maps) {
        Item item = new Item(commandParsed[1], Double.parseDouble(commandParsed[2]), commandParsed[3]);
        String mapName = commandParsed[3];
        Map<String, Item> map = new HashMap<>();
        if (inventory.contains(item)) {
            System.out.printf("Error: Item %s already exists%n", item.name);
        } else {
            inventory.add(item);
            System.out.printf("Ok: Item %s added successfully%n", item.name);
             maps.computeIfAbsent(mapName, k -> new HashMap<>()).put(item.name, item);
        }
    }

我的想法是将所有唯一的项目添加到一个集合中,然后将 Map<String, Map<String, Item>> maps键设置为添加项目的类型和要映射的值,其中包含该类型的所有项目,但键是项目名称。然而,内部映射的键再次是项目的类型。这是一些示例输入

add CowMilk 1.90 dairy
add BulgarianYogurt 1.90 dairy

我试图找出为什么我的内部地图key-value pair不是<item.name, Item><item.type, Item>因为我的代码是.put(item.name, item);

这是我的 Item 类构造函数

 public Item(String name, double price, String type) {
        this.name = name;
        this.price = price;
        this.type = type;
    }

在此处输入图像描述

标签: javahashmap

解决方案


您误读了调试器对象树显示。

映射条目是键值对

"dairy"映射条目是键值对,键为“dairy”,值是另一个映射(键为“CowMilk”和“BulgarianYogurt” )

所以不是内部映射有一个“dairy”键,只是扩展“dairy”映射条目将“dairy”暴露为映射条目中的。内图的键是“CowMilk”和“BulgarianYogurt”。


推荐阅读