Java中重写object下的equals方法

来源:互联网 发布:长沙学历网络教育报考 编辑:程序博客网 时间:2024/06/15 14:54
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);    }}
0 0
原创粉丝点击