java equals函數詳解

equals函數在基類object中已經定義,源碼如下
 public boolean equals(Object obj) {
        return (this == obj);
    }

從源碼中可以看出默認的equals()方法與“==”是一致的,都是比較的對象的引用,而非對象值(這裏與我們常識中equals()用於對象的比較是相餑的,原因是java中的大多數類都重寫了equals()方法,下面已String類舉例,String類equals()方法源碼如下:)

    /** The value is used for character storage. */
    private final char value[];

    /** The offset is the first index of the storage that is used. */
    private final int offset;

    /** The count is the number of characters in the String. */
    private final int count;

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;
    }

String類的equals()非常簡單,只是將String類轉換爲字符數組,逐位比較。

綜上,使用equals()方法我們應當注意:

 1. 如果應用equals()方法的是自定義對象,你一定要在自定義類中重寫系統的equals()方法。

 2. 小知識,大麻煩。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章