JAVA面試題:equals()方法和== 區別

來源:互聯網
上載者:User

標籤:

http://bbs.csdn.net/topics/390000725

 

總結:

equals在沒重寫之前和==一樣,重寫之後,equals只要內容一樣即為true

equals跟==一般情況下是等價的,但是對於String類型,它重寫了equals方法,比較的是內容。預設情況下兩個都是比較的引用地址,除非你重寫equals方法。

 

equals源碼:

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

版主解答:

“但是經常說==兩邊對象是按地址在比較,而equals()是按內容在比較”這句話在排除根類Object以及沒有自己重寫equals方法的情況下是對的。

即Object類中equals的實現就是用的==
其他繼承Object的equals方法基本上都重寫了這個方法,比如String類的equals方法:

XML/HTML code ?
123456789101112 equalspublic boolean equals(Object anObject)Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.  Overrides:equals in class ObjectParameters:anObject - The object to compare this String against Returns:true if the given object represents a String equivalent to this string, false otherwiseSee Also:compareTo(String), equalsIgnoreCase(String)



這是String的equals方法源碼:

Java code ?
12345678910111213141516171819202122 public boolean equals(Object obj)    {        if(this == obj)            return true;        if(obj instanceof String)        {            String s = (String)obj;            int i = count;            if(i == s.count)            {                char ac[] = value;                char ac1[] = s.value;                int j = offset;                int k = s.offset;                while(i-- != 0                    if(ac[j++] != ac1[k++])                        return false;                return true;            }        }        return false;    }

 

JAVA面試題:equals()方法和== 區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.