Java equals() & ==

來源:互聯網
上載者:User

標籤:null   amp   turn   character   seq   value   public   equals   ecif   

Java中equals() & ==的異同,可以通過翻閱JDK源碼java.lang.String.equals(Object anObject)的來獲得一個感性認識:

 

 1 /** 2      * Compares this string to the specified object.  The result is {@code 3      * true} if and only if the argument is not {@code null} and is a {@code 4      * String} object that represents the same sequence of characters as this 5      * object. 6      * 7      * @param  anObject 8      *         The object to compare this {@code String} against 9      *10      * @return  {@code true} if the given object represents a {@code String}11      *          equivalent to this string, {@code false} otherwise12      *13      * @see  #compareTo(String)14      * @see  #equalsIgnoreCase(String)15      */16     public boolean equals(Object anObject) {17      if (this == anObject) {18          return true ;19      }20      if (anObject instanceof String) {21          String anotherString = (String)anObject;22          int n = count ;23          if (n == anotherString.count ) {24            char v1[] = value ;25            char v2[] = anotherString.value ;26            int i = offset ;27            int j = anotherString.offset ;28            while (n-- != 0) {29               if (v1[i++] != v2[j++])30                return false ;31           }32            return true ;33          }34      }35      return false;36     }

從上面可以看到java.lang.String.equals(Object anObject)方法返回true的情況:

  1. 自己與自己比較;
  2. 兩個對象都是String,且內容相同。

 

需要注意的:

  1. Java不支援運算子多載(Operator Overloading);
  2. Java中equals()和hashCode()緊密聯絡,這兩個方法被重寫(Overriding),所以equals()的的具體含義要看代碼實現。

 

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.