Java 中equals 和== 的区别

来源:互联网 发布:java版手机qq2013 编辑:程序博客网 时间:2024/05/15 02:23

疑问: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;}

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

0 0
原创粉丝点击