gpt4 book ai didi

java - 我的哈希码不起作用 - 是我的 equals() 有问题吗?

转载 作者:太空宇宙 更新时间:2023-11-04 14:01:32 25 4
gpt4 key购买 nike

每当我尝试运行该程序时,我都会得到以下输出:

6150

5000

1015612567

列表中的人员:

{A=100,B=50}

下一个:

人:A 哈希码:507806258 值:100

下一个:

人:B 哈希码:507806309 值:50

String name;
int day;

static Map<String, Integer> people = new HashMap<>();

public PeopleHash(String name, int day) {
this.name = name;
this.day = day;

}

public String getName() {
return name;
}

public int getDay() {
return day;
}

public boolean equals(PeopleHash other) {
if (other instanceof PeopleHash) {
PeopleHash d = (PeopleHash)other;
return name == d.name && day == d.day;
} else {
return false;
}
}

@Override
public int hashCode() {
return 50 * day;
}

public PeopleHash peopleEntry(){
String namn = "A";
int schiffre = 123;
return null;
}


public static void main(String[] args) {


PeopleHash p1 = new PeopleHash("Isolde", 123);
PeopleHash p2 = new PeopleHash("Jean", 100);

people.put("Person A", 100);
people.put("Person B", 50);



System.out.println(p1.hashCode());
System.out.println(p2.hashCode());



System.out.println("People in list: \n" + people);

for (Entry<String, Integer> entry : people.entrySet()) {
String a = entry.getKey();
int b = entry.getValue();

System.out.println("Next:");
System.out.println("Person: " + a + " Hashcode: " + entry.hashCode() + " Value: " + b);

}

}

}

我做错了什么?

最佳答案

哈希/等于本身没问题。问题在于使用(或缺乏)。

“Person:”输出显示 Map.Entry 的哈希码对象( entry.hashCode() ),并且与 p1/p2 没有关系。映射中的条目是通过字符串键添加的,并且 p1/p2 对象会被简单地丢弃。

map 可能应该声明为 Map<HashPerson, Integer>这样将使用 HashPerson 的 equals/hashCode 。单个 person 对象应直接用作键:

people.add(p1, 1234);

那么循环可以写成这样:

for (Entry<HashPerson, Integer> entry : people.entrySet()) {
HashPerson person = entry.getKey();
Integer value = entry.getValue();

System.out.println(
String.format("Person %s HashCode: %d Value: %d",
person.getName(), person.hashCode(), value));
}

关于java - 我的哈希码不起作用 - 是我的 equals() 有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29261202/

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