您的位置:首页 > 移动开发 > Objective-C

Java中重写object下的equals方法

2016-12-04 14:51 495 查看
package practice;

/**
* Created by fangjiejie on 2016/12/4.
*/
public class BB {
int b1;
String b2;

public BB(int b1, String b2) {
this.b1 = b1;
this.b2 = b2;
}
public static void main(String[] args) {
BB a1=new BB(666,"hello");
BB a2=new BB(666,"hello");
System.out.println(a1==a2);//结果为false,比较的是堆地址
System.out.println(a1.equals(a2));//按理说equals比较的是内容,但结果返回false
//object下的equals是有缺陷的需要我们来重写
}
}

class EE{
int c1;
String c2;
public EE(String c2, int c1) {
this.c2 = c2;
this.c1 = c1;
}

@Override
public boolean equals(Object obj) {
if(this==obj){//两者的堆地址相同
return true;
}
if(obj==null){//被比对象为空,则无法比较
return false;
}
if(this.getClass()!=obj.getClass()){//getClass返回的是运行时类,运行时类不是同一个无法比较哦
return false;
}
EE obje=(EE)obj;//为了控制被比对象和比较对象具有相同的属性,然后比较属性的值
return this.c1==obje.c1 && this.c2.compareTo(obje.c2)==0;
}

public static void main(String[] args) {
EE c1=new EE("hello",666);
EE c2=new EE("hello",666);
System.out.println(c1==c2);//false
System.out.println(c1.equals(c2));//true
EE c3=new FF("hello",666);
FF c4=new FF("hello",666);
FF c5=new FF("hello",666);
System.out.println(c1.equals(c3));//false,getClass不同
System.out.println(c3.equals(c4));//true
System.out.println(c4.equals(c5));//true 在重写equals方法中c5被强转为EE类型,然而比较对象是EE的子类FF类型
// 所以我们可以比较父类中属性值是否相等的情况,来作为equals的比较标准
}
}
class FF extends EE{
FF(String c2, int c1){
super(c2,c1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  equals java