我正在更深入地学习哈希码,并认为:
1.如果重写equals(),则必须覆盖hashcode().
2.要查找2个对象是否是同一个对象,请使用==运算符
考虑到这两个因素,在Java中我假设当== operator用于比较2个实例是否相同时,
if(object1 == object2)
Run Code Online (Sandbox Code Playgroud)
实际上是在做
if(object1.hashcode() == object2.hashcode())
Run Code Online (Sandbox Code Playgroud)
但是通过下面的测试看起来我错了.
public class Main {
public static void main(String[] args){
Obj1 one = new Obj1();
Obj1 two = new Obj1();
//is this calling hashCode() in backend???
if(one == two) {
System.out.println("same");
}
else {
System.out.println("nope");
}
//this is of course return true
if(one == one) {
System.out.println("one and one is same");
}
}
}
class Obj1 {
@Override
public int hashCode() {
System.out.println("hashCode() is called"); …Run Code Online (Sandbox Code Playgroud)