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


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
 
?
1
2
3
4
5
6
7
8
9
10
11
12
equals
public 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 Object
Parameters:
anObject - The object to compare this String against 
Returns:
true if the given object represents a String equivalent to this string, false otherwise
See Also:
compareTo(String), equalsIgnoreCase(String)



這是String的equals方法源碼:

Java code
 
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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 ;
     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM