package test;
/**
* 解答:两个对象值相同(x.equals(y) == true),但却可有不同的hash code,这句话对不对?
* 这句话是对的,因为equals是可以覆盖的,所以可以使(x.equals(y) == true),且x,y有不同hash code
*/
public class EqualAndHashCode {
public static void main(String[] args) {
A a1 = new A(1);
A a2 = a1;//new A(1);
boolean flag1 = a1==a2;
System.out.println(a1.equals(a2)+" "+flag1);
System.out.println(a1.hashCode());
System.out.println(a2.hashCode());
B b1 = new B(1);
B b2 = new B(1);
boolean flag2 = b1==b2;
System.out.println(b1.equals(b2)+" "+flag2);
System.out.println(b1.hashCode());
System.out.println(b2.hashCode());
}
}
class A{
int a;
public A(int i){
this.a = i;
}
}
class B{
int b;
public B(int i){
this.b = i;
}
@Override
public boolean equals(Object obj) {
if(this.b==((B)obj).b)return true;
else return false;
}
}
不用equal而用“==”才不对。