gpt4 book ai didi

java - 将 Hashmap 与自定义内部类一起使用时出现问题

转载 作者:行者123 更新时间:2023-12-01 05:42:21 24 4
gpt4 key购买 nike

我的代码如下所示:

private void MethodToDo(SpecialObject o) {
Map<InfoObj, Integer> totalNeeds = new HashMap<InfoObj, Integer>();

for (ListObject obj : o.getListOfObjects()) {
InfoObj infoObj = new InfoObj(obj.getTitle(), obj.getId());
Integer need = totalNeeds.get(infoObj);

if (need == null) {
need = new Integer(obj.getNeeded());
} else {
need = need + obj.getNeeded();
}
totalNeeds.put(infoObj, need);
}
}

该对象是一个私有(private)内部类(与该方法位于同一类中),如下所示:

private class InfoObj {
private String title;
private Integer id;

public InfoObj(String title, Integer id) {
this.title = title;
this.id = id;
}

public String getTitle() {
return title;
}

public Integer getId() {
return id;
}

@Override
public boolean equals(Object io2) {
if (this == io2) { return true; }
if ( !(io2 instanceof InfoObj) ) { return false; }
InfoObj temp = (InfoObj) io2;
return this.id.equals(temp.id) && this.title.equals(temp.title);
}

@Override
public int hashCode() {
final int prime = 7;
int result = 1;
result = prime * result
+ ((this.title == null) ? 0 : this.title.hashCode());
result = prime * result
+ ((this.id == null) ? 0 : this.id.hashCode());
return result;
}

但是,尽管重写了 equals 和 hashCode 方法,hashMap 仍将包含重复键(如 title 和 id 是等效的......但仍显示在多个位置)。我认为我做的一切都是正确的,但意识到我可能会遗漏一些东西......

此外,我知道存在重复键,因为我循环遍历 keySet 并输出结果,这会导致具有相同标题和 id 的对象多次出现。

最佳答案

根据您的评论,HashMap 不能包含相同键的实现,相同的键将是:

(e.hash == hash && ((k = e.key) == key || key.equals(k)))

由于您遵循 equals 和 hashcode 的约定,因此您在此处创建的任何对象:

InfoObj infoObj = new InfoObj(obj.getTitle(), obj.getId());

具有相同的 id 和标题,将被视为相同的key,并且如果 map 之前包含该键的映射,则旧值将被替换。

关于java - 将 Hashmap 与自定义内部类一起使用时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6793606/

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