每当我尝试运行此程序时,我都会得到以下输出:
6150
5000
1015612567
列表中的人物:
{人A = 100,人B = 50}
下一步:
人:人A哈希码:507806258价值:100
下一步:
人:人B Hashcode: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);
}
}
}
我做错了什么?
答案 0 :(得分:0)
hash / equals本身没问题。问题在于使用(或缺乏)。
'Person:'输出显示Map.Entry对象(entry.hashCode()
)的哈希码,与p1 / p2无关。地图中的条目由字符串键添加,并且p1 / p2对象被忽略。
Map可能应该声明为Map<HashPerson, Integer>
,以便使用HashPerson的equals / hashCode。个人对象应直接用作键:
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));
}
答案 1 :(得分:0)
对于equals方法肯定存在问题。试试这个 -
public boolean equals(Object other) {
if (other instanceof PeopleHash) {
PeopleHash d = (PeopleHash)other;
return name.equals(d.name) && day == d.day;
}
return false;
}
答案 2 :(得分:0)
要比较对象,请使用Object.equals(Object)方法。您已使用签名PeopleHash.equals(PeopleHash)定义了一个新方法。
将方法签名更改为
@Override
public boolean equals(Object other) {
始终建议添加@Override注释,因为如果您定义的方法没有覆盖其他方法,编译器会发出警告。