String類的equal方法


先來看這個方法的英文注釋

/** * Compares this string to the specified object. The result is {@code * true} if and only if the argument is not {@code null} and is a {@code * String} object that represents the same sequence of characters as this * object. * * @param anObject * The object to compare this {@code String} against * * @return {@code true} if the given object represents a {@code String} * equivalent to this string, {@code false} otherwise * * @see #compareTo(String) * @see #equalsIgnoreCase(String) */

英文不好的同學不用擔心,讓我用自己蹩腳的英文翻譯下。

這個方法用來對比當前字符串和指定對象是否相等。當且僅當指定對象當前字符串擁有的相同字符序列時,這個方法才返回true。

接着我們再來看下這個方法的源碼:

public boolean equals(Object anObject) { //如果是同一個對象(內存地址一樣),則直接返回true
        if (this == anObject) { return true; } /*判斷指定對象是否為字符串類型,不是的話直接返回false; 是字符串類型類型的話,將當前字符串和指定對象轉換為對 應的字符數組,然后通過while循環遍歷兩個相同位置的字符數組元素是否相同,只要有一個不同則直接返回false;否則返回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; }

是不是很簡單哈!


免責聲明!

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



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