1. 程式人生 > >Java還要再學一遍基礎(三)hashCode方法

Java還要再學一遍基礎(三)hashCode方法

瞭解Java的hashCode方法

hashCode()是什麼?

hashCode()方法是Object類中就有的一個方法。
  public native int hashCode();
該方法是native方法,意味著這個方法的實現是依賴於底層的,普遍認為Object類中的方法返回的是這個物件的實體地址。

看看這個方法的描述:

Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by
java.util.HashMap.

位這個物件返回一個hash code,這個方法主要效力於比如HashMap等雜湊表。
Object類中對hashcode方法特性的描述(英語翻譯的不好):

  • 同一個物件多次呼叫將返回相同的hash code
  • 如果兩個物件是相等的,也就是equals(Object)方法返回true的話,分別呼叫這兩個物件的hashCode()方法應該返回相同的結果。
  • 如果兩個物件不相等,也就是equals(Object)方法返回false的話,分別呼叫這兩個物件的hashCode()方法並不要求返回相同的結果。然而程式設計師應當意識到為不相同的物件提供能返回獨有的hash code的方法能提高程式效率。

再看看Object類中的equels()方法:

public boolean equals(Object obj) {
        return (this == obj);
    }

很明顯Object類中的equals()方法是直接比較的兩個物件的引用是否相等,也就是地址是否相等。與上述描述吻合。

從上面可以看出hashCode()方法的作用主要是為一些具有雜湊表結構的功能服務的,以及兩個物件如果相同必定返回相同的hash code。並且Object類自帶的hashCode()方法可以認為就是返回獨有的結果。

String物件中的hashCode()方法。

先看String類的一些資訊:

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

    /** Cache the hash code for the string */
    private int hash; // Default to 0

可以知道:

  • String是final修飾的,因此不能被繼承。
  • String實現了Serializable(可序列化介面),Comparable(可比較的),CharSequence (字元序列介面)。
  • String的內部是由一個char[]實現的。
  • String有個hash屬性,預設值是0;

再看看equals()方法:

public boolean equals(Object anObject) {
        if (this == anObject) {
            return 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;
    }

String重寫了Object的equals()方法。實現原理很簡單,如果物件地址不同,也就是一個一個字元的判斷是否 相等。

再看看hashCode()方法:

public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

看看hashCode()方法的描述:

Returns a hash code for this string. The hash code for a String object is computed as 

 s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)

配合程式碼便可以看出,String的hash code的生成公式:

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

其中n是char[]的length,也就是31* 每個字元 *的總和。