问题描述
-
我同时覆盖了hashCode()和equals(),但是我不修改覆盖方法内的任何内容.
@Override
public int hashCode() {
int hash = 7;
hash = 67 * hash + Objects.hashCode(this.model);
hash = 67 * hash + this.year;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final PC other = (PC) obj;
if (!Objects.equals(this.model, other.model)) {
return false;
}
if (this.year != other.year) {
return false;
}
return true;
}
我创建了两个相同的对象:
I create 2 identical objects:
PC One = new PC();
One.setModel("HP");
One.setYear(2013);
PC Two = new PC();
Two.setModel("HP");
Two.setYear(2013);
我比较这两个对象:
I compare those 2 objects:
if (One.equals(Two)) {
System.out.println("They are the same objects!");
} else {
System.out.println("They are different objects!");
}
结果是:它们是相同的对象!".但是,如果我不重写这两种方法,结果将是:它们是不同的对象!". 因为hashCode对于每个对象都是唯一的(我想),所以我期望结果是:它们是不同的对象!".问:为什么?
The result is: "They are the same objects!". However, if I don't override both methods, the result will be: "They are different objects!". Because the hashCode is unique for each object (I suppose), I have expected thet the result to be: "They are different objects!".Q: Why?
推荐答案
Object
的默认equals
实现使用实例的引用地址.两个Objects
仅在它们位于内存中的相同位置时才相等.
The default equals
implementation of Object
uses the instance's reference address. Two Objects
are equal ONLY if they reside at the same location in memory.
如果不重写equals
,则将获得实现.
If you don't override equals
that is the implementation you get.
此外,此行为与hashCode
无关,因为您没有调用hashCode
.如果直接调用equals
,则不会使用hashCode
. hashCode
通常与HashMap
一样在数据结构中使用.
Also, this behavior has nothing to do with hashCode
is you are not calling hashCode
. If you call equals
directly there is not use of hashCode
. hashCode
is generally used in data structures just as HashMap
.
这篇关于重写hashCode()和equals()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!