gpt4 book ai didi

Java调整嵌套Hashmap值

转载 作者:行者123 更新时间:2023-12-01 07:01:03 25 4
gpt4 key购买 nike

我试图使用此处给出的想法来调整嵌套 HashMap ,但我的解决方案不起作用:How to update a value, given a key in a java hashmap? 。我的嵌套 HashMap 是 shoppingLists。它包含作为键的购物列表 listID 的外部 HashMap 和作为值的项目的 HashMap 。项目 HashMap 包含 itemName 作为键,项目的数量作为值。 adjustItemAmount 尝试将项目的数量调整给定数量 x

HashMap<String, HashMap<String, Integer>> shoppingLists = new HashMap<>();

public void adjustItemAmount(String itemName, int x, String listID) {
int current_amount = shoppingLists.get(listID).get(itemName);
HashMap<String, Integer> items = shoppingLists.get(listID);
HashMap updatedItems = items.put(itemName, items.get(itemName) + x);
shoppingLists.put(listID, updatedItems);
}

HashMap UpdatedItems = items.put(itemName,items.get(itemName)+x); 表明 Java 需要一个 hashmap,但会获取一个整数。我不明白这是怎么回事。

最佳答案

HashMap的put方法不返回HashMap。它返回值。因此这一行是不正确的:

    HashMap updatedItems= items.put(itemName,items.get(itemName)+x);

返回类型将为 Integer,因为项目映射为 <String, Integer>类型。

关于Java调整嵌套Hashmap值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51758793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com