Java 中equals 和== 的区别

2017-01-14 08:44:49来源:CSDN作者:zgengen人点击

第七城市

疑问:equals 和==是用来干什么的?
1:比较8种基本数据类型的引用地址,是否一样
2:比较引用对象的内容,即堆的内存地址,是否一样

疑问:两者区别?

public boolean equals(Object o) {   return this == o;}

如果不重写equals 两者是没有区别的。
分析下String中两者的区别

String a = "abc";String b = "abc";String c = a;String d = new String("abc");PrinterUtil.log("a == b =" + (a==b));PrinterUtil.log("a equals b =" + (a.equals(b)));PrinterUtil.log("b == c =" + (b==c));PrinterUtil.log("b equals c =" + (b.equals(c)));PrinterUtil.log("d == c =" + (d==c));PrinterUtil.log("d equals c =" + (d.equals(c)));

输出结果

a == b =truea equals b =trueb == c =trueb equals c =trued == c =falsed equals c =true

“abc”是一块内存地址,new String(“abc”)又重新分配来一块内存地址,故d==c 等于false,equals 之所以等于true,看下源码

public boolean equals(Object anObject) {    if (this == anObject) {        return true;    }    if (anObject instanceof String) {        String anotherString = (String)anObject;        int n = value.length;        if (n == anotherString.value.length) {            char v1[] = value;            char v2[] = anotherString.value;            int i = 0;            while (n-- != 0) {                if (v1[i] != v2[i])                    return false;                i++;            }            return true;        }    }    return false;}

疑问:怎么获取对象的引用地址?

第七城市

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台