62,614
社区成员
发帖
与我相关
我的任务
分享
class Test1{
int i;
}
public class Test2{
public static void main(String[] args){
Test1 t1 = new Test1();
Test1 t2 = new Test1();
t1.i = t2.i = 100;
System.out.println(t1.equals(t2));
}
}
public boolean equals(Object obj) {
return (this == obj);
}
public class EqTest {
private int i;
public boolean equals(Object obj) { //覆盖了超类继承下来的 equals 方法来实现自己真正的相等性测试
if (obj == this) return true; //如果引用都相等那这两个就是同一个对象,当然自己与自己相等
if (obj == null) return false; //如果传进来空引用,那就不必比较了,真实的对象肯定同虚无不相等
if (obj.getClass() != this.getClass()) return false; //如果两个对象不是同类就根本没有可比性,当然不等
EqTest other = (EqTest) obj; //将 obj 强制转换为它实际的类型
return other.i == this.i; //根据两个属于同一个类的不同对象的实例域的值来判断这两个对象是否相等
}
public static void main(String[] args) {
EqTest t1 = new EqTest();
EqTest t2 = new EqTest();
t1.i = t2.i = 100;
System.out.println(t1.equals(t2));
}
}