天天看點

開發日常小結(34):源碼分析:String類的equals()方法

目錄

​​1、提出問題​​

​​2、源碼分析​​

​​3、測試Demo:​​

1、提出問題

我們都知道,在Java中,“==”比較的是對象在記憶體中的位址,“equals”比較對象的内容;今天複習一下”equals“。

2、源碼分析

    /**

     * 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)

     */

public boolean equals(Object anObject) {
        //First:比較兩個對象是否是同一個對象,則直接return true;
        if (this == anObject) {
            return true;
        }

        //Second:如果被比較的對象是String類型,則繼續
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            
            //Third:比較兩者的長度
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;

                //Forth:比較兩者元素是否相同
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }      

3、測試Demo:

public class test_equals {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
     String a="1234";
         String b="1234";
         String c = new String("1234");
         System.out.println("a==b: "+(a==b));
         System.out.println("a==c: "+(a==c));
         System.out.println("a.equals(c): "+(a.equals(c)));
  }

}