HashMap 获取键值的意外字符串

HashMap getting unintended string for key value

我有这段代码:

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);

这是我的项目class构造器

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

I am trying to find out why my inner map key-value pair is not <item.name, Item> but <item.type, Item> since my code is .put(item.name, item);

你需要把{item.name, item}放在内图里面,如下图:

maps.computeIfAbsent(mapName, k -> new HashMap<String, Item>().put(item.name, item));

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

地图条目是 key-value 对

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

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