java - 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;
}
解决方案
您误读了调试器对象树显示。
映射条目是键值对。
"dairy"
映射条目是键值对,键为“dairy”,值是另一个映射(键为“CowMilk”和“BulgarianYogurt” )
所以不是内部映射有一个“dairy”键,只是扩展“dairy”映射条目将“dairy”暴露为映射条目中的键。内图的键是“CowMilk”和“BulgarianYogurt”。
推荐阅读
- excel - 如何使用谷歌表格中的公式 countif () 获取包含该值的特定行号
- python - aiogram bot 如何请求用户的位置?
- python - 我想将字典列表写入 txt 文件
- firebase - ASP.NET Core 更新 HttpContext.User
- python - 如何在 Appium 的多个测试之间保持登录状态?
- python - 使用 Pytorch 库主机名的 Deepspeed -I 错误
- python - 如何捕获 DynamoDB ResourceInUseException Python?
- asyncapi - AsyncAPI 中的关联 ID 是什么?
- javascript - 使用纯 JavaScript 从 URL 获取部分 JSON
- c# - AutoMapper - 整数列表到对象列表