gpt4 book ai didi

java - 可以对HashMap中的对象值求和吗?

转载 作者:行者123 更新时间:2023-12-02 05:18:48 27 4
gpt4 key购买 nike

我刚刚开始在 Java 中使用 HashMap,我想知道是否可以对 HashMap 中的对象值求和。

我已经使用 ArrayList 完成了此操作,如下所示:

private int totalWeight() {
int totalWeight = 0;
for(Item item : items){
totalWeight += item.getWeight();
}
return totalWeight;
}

我有不同的具有权重值的对象,并且我尝试将权重的总值作为totalWeight返回,但似乎无法使用HashMap这样做。

最佳答案

你可以尝试这样的事情

public class HMTest {

public static void main(String[] args) {

int totalWeight = 0;
HashMap<String, Item> map = new HashMap<String, Item>();
map.put("Key1", new Item(10));
map.put("Key2", new Item(20));
map.put("Key3", new Item(30));

Collection<Item> values = map.values();

for (Item i : values) {
totalWeight += i.getWeight();
}

System.out.println("Total Weight :" + totalWeight);

}

}

class Item {
private int weight;

public Item(int weight) {
this.weight = weight;
}

public int getWeight() {
return weight;
}

public void setWeight(int weight) {
this.weight = weight;
}

}

关于java - 可以对HashMap中的对象值求和吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29109152/

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