Java的hashCode方法

來源:互聯網
上載者:User

標籤:

 0 Java的hashCode方法概述
    In the Java programming language, every class implicitly or explicitly provides a hashCode() method, which digests the data stored in an instance of the class into a single hash value (a 32-bit signed integer). Technically, in Java, hashCode() by default is a native method, meaning, it has the modifier ‘native‘, as it is implemented directly in the native code in the JVM. (使用native關鍵字說明這個方法是原生函數,也就是這個方法是用C/C++語言實現的,並且被編譯成了DLL,由java去調用。native關鍵字介紹)
    All the classes inherit a basic hash scheme from the fundamental base class java.lang.Object, but instead many override this to provide a hash function that better handles their specific data. Classes which provide their own implementation must override the object method public int hashCode().
1  Object類的hashCode()
public int hashCode()
返回該對象的雜湊碼值。支援此方法是為了提高雜湊表(例如  java.util.Hashtable 提供的雜湊表)的效能。

hashCode 的常規協定是:

  • 在 Java 應用程式執行期間,在對同一對象多次調用 hashCode 方法時,必須一致地返回相同的整數,前提是將對象進行 equals 比較時所用的資訊沒有被修改。從某一應用程式的一次執行到同一應用程式的另一次執行,該整數無需保持一致。
  • 如果根據 equals(Object) 方法,兩個對象是相等的,那麼對這兩個對象中的每個對象調用 hashCode 方法都必鬚生成相同的整數結果。
  • 如果根據 equals(java.lang.Object) 方法,兩個對象不相等,那麼對這兩個對象中的任一對象上調用 hashCode 方法 要求一定產生不同的整數結果。但是,程式員應該意識到,為不相等的對象產生不同整數結果可以提高雜湊表的效能。

實際上,由 Object 類定義的 hashCode 方法確實會針對不同的對象返回不同的整數。(這一般是通過將該對象的內部地址轉換成一個整數來實現的,但是 JavaTM 程式設計語言不需要這種實現技巧。) 附equals方法和hashCode方法的詳解。

2  常用類的hashCode()2.1 Integer類的hashCode()
java.lang.Object
        java.lang.Number
              java.lang.Integer
public int hashCode()
     覆蓋:類 Object 中的 hashCode
     返回:該對象的雜湊碼值,它的值即為該Integer對象表示的基本 int 類型的數值
2.2 String類的hashCode()
java.lang.Object
java.lang.String
public int hashCode()
     覆蓋:類 Object 中的 hashCode
     返回:該對象的雜湊碼值。String 對象的雜湊碼根據以下公式計算:
                        
即:h(s)=s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1];
     使用int演算法,這裡s[i]是字串的第i個字元,n是字串的長度,^表示求冪。(Null 字元串的雜湊值為0)
 

Java的hashCode方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.