【Java實戰】源碼解析為什麼覆蓋equals方法時總要覆蓋hashCode方法

來源:互聯網
上載者:User

標籤:bucket   param   條件   main   class   預設   ble   替換   line   

1、背景知識

本文代碼基於jdk1.8分析,《Java編程思想》中有如下描述:

另外再看下Object.java對hashCode()方法的說明:

/**     * Returns a hash code value for the object. This method is     * supported for the benefit of hash tables such as those provided by     * {@link java.util.HashMap}.     * <p>     * The general contract of {@code hashCode} is:     * <ul>     * <li>Whenever it is invoked on the same object more than once during     *     an execution of a Java application, the {@code hashCode} method     *     must consistently return the same integer, provided no information     *     used in {@code equals} comparisons on the object is modified.     *     This integer need not remain consistent from one execution of an     *     application to another execution of the same application.     * <li>If two objects are equal according to the {@code equals(Object)}     *     method, then calling the {@code hashCode} method on each of     *     the two objects must produce the same integer result.     * <li>It is <em>not</em> required that if two objects are unequal     *     according to the {@link java.lang.Object#equals(java.lang.Object)}     *     method, then calling the {@code hashCode} method on each of the     *     two objects must produce distinct integer results.  However, the     *     programmer should be aware that producing distinct integer results     *     for unequal objects may improve the performance of hash tables.     * </ul>     * <p>     * As much as is reasonably practical, the hashCode method defined by     * class {@code Object} does return distinct integers for distinct     * objects. (This is typically implemented by converting the internal     * address of the object into an integer, but this implementation     * technique is not required by the     * Java? programming language.)     *     * @return  a hash code value for this object.     * @see     java.lang.Object#equals(java.lang.Object)     * @see     java.lang.System#identityHashCode     */    public native int hashCode();

對於3點約定翻譯如下:

1)在java應用執行期間,只要對象的equals方法的比較操作所用到的資訊沒有被修改,那麼對這同一對象調用多次hashCode方法都必須始終如一地同一個整數。在同一個應用程式的多次執行過程中,每次執行該方法返回的整數可以不一致。

2)如果兩個對象根據equals(Object)方法比較是相等的,那麼調用這兩個對象中任意一個對象的hashCode方法都必須產生同樣的整數結果。

3)如果兩個對象根據equals(Object)方法比較是不相等的,那麼調用這兩個對象中任意一個對象的hashCode方法沒必要產生不同的整數結果。但是程式猿應該知道,給不同的對象產生截然不同的整數結果,有可能提高散列表(hash table)的效能。


因此,覆蓋equals時總是要覆蓋hashCode是一種通用的約定,而不是必須的,如果和基於散列的集合(HashMap、HashSet、HashTable)一起工作時,特別是將該對象作為key值的時候,一定要覆蓋hashCode,否則會出現錯誤。那麼既然是一種規範,那麼作為程式猿的我們就有必要必須執行,以免出現問題。

下面就以HashMap為例分析其必要性

2、HashMap內部實現

常用形式如下:

public class PhoneNumber {    private int areaCode;    private int prefix;    private int lineNumber;    public PhoneNumber(int areaCode, int prefix, int lineNumber) {        this.areaCode = areaCode;        this.prefix = prefix;        this.lineNumber = lineNumber;    }        @Override    public boolean equals(Object o) {        if (this == o) return true;        if (o == null || getClass() != o.getClass()) return false;        PhoneNumber that = (PhoneNumber) o;        if (areaCode != that.areaCode) return false;        if (prefix != that.prefix) return false;        return lineNumber == that.lineNumber;    }    @Override    public int hashCode() {        int result = areaCode;        result = 31 * result + prefix;        result = 31 * result + lineNumber;        return result;    }    public static void main(String[] args){        Map<PhoneNumber,String> phoneNumberStringMap = new HashMap<PhoneNumber,String>();  1)初始化        phoneNumberStringMap.put(new PhoneNumber(123, 456, 7890), "honghailiang");         2)put儲存        System.out.println(phoneNumberStringMap.get(new PhoneNumber(123, 456, 7890)));     3)get擷取    }}
1)初始化
/**     * Constructs an empty <tt>HashMap</tt> with the default initial capacity     * (16) and the default load factor (0.75).     */    public HashMap() {        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted    }

建立一個具有預設負載因子的HashMap,預設負載因子是0.75

2)put儲存

/**     * Associates the specified value with the specified key in this map.     * If the map previously contained a mapping for the key, the old     * value is replaced.     *     * @param key key with which the specified value is to be associated     * @param value value to be associated with the specified key     * @return the previous value associated with <tt>key</tt>, or     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.     *         (A <tt>null</tt> return can also indicate that the map     *         previously associated <tt>null</tt> with <tt>key</tt>.)     */    public V put(K key, V value) {        return putVal(hash(key), key, value, false, true);    }

通過注釋可以看出,key值相同的情況下,會將前者覆蓋,也就是HashMap中不允許存在重複的Key值。並且該方法是有傳回值的,返回key值的上一個value,如果之前沒有map則返回null。繼續看putVal

/**     * Implements Map.put and related methods     *     * @param hash hash for key     * @param key the key     * @param value the value to put     * @param onlyIfAbsent if true, don‘t change existing value     * @param evict if false, the table is in creation mode.     * @return previous value, or null if none     */    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,                   boolean evict) {        Node<K,V>[] tab; Node<K,V> p; int n, i;        if ((tab = table) == null || (n = tab.length) == 0)      //tab為空白則建立            n = (tab = resize()).length;        if ((p = tab[i = (n - 1) & hash]) == null)               //根據下標擷取,如果沒有(沒發生碰撞(hash值相同))則直接建立            tab[i] = newNode(hash, key, value, null);        else {                                                   //如果發生了碰撞進行如下處理            Node<K,V> e; K k;            if (p.hash == hash &&                ((k = p.key) == key || (key != null && key.equals(k))))                e = p;            else if (p instanceof TreeNode)                      //為紅黑數的情況                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);            else {                                               //為鏈表的情況,普通Node                for (int binCount = 0; ; ++binCount) {                    if ((e = p.next) == null) {                        p.next = newNode(hash, key, value, null); //鏈表儲存                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st                            treeifyBin(tab, hash);                //如果鏈表長度超過了8則轉為紅/黑樹狀結構                         break;                    }                    if (e.hash == hash &&                        ((k = e.key) == key || (key != null && key.equals(k))))                        break;                    p = e;                }            }            if (e != null) { // existing mapping for key                     // 寫入,並返回oldValue                V oldValue = e.value;                if (!onlyIfAbsent || oldValue == null)                    e.value = value;                afterNodeAccess(e);                return oldValue;            }        }        ++modCount;        if (++size > threshold)          // 超過load factor*current capacity,resize            resize();        afterNodeInsertion(evict);        return null;    }


可以看到第一個參數時key的hash,如下

/**     * Computes key.hashCode() and spreads (XORs) higher bits of hash     * to lower.  Because the table uses power-of-two masking, sets of     * hashes that vary only in bits above the current mask will     * always collide. (Among known examples are sets of Float keys     * holding consecutive whole numbers in small tables.)  So we     * apply a transform that spreads the impact of higher bits     * downward. There is a tradeoff between speed, utility, and     * quality of bit-spreading. Because many common sets of hashes     * are already reasonably distributed (so don‘t benefit from     * spreading), and because we use trees to handle large sets of     * collisions in bins, we just XOR some shifted bits in the     * cheapest possible way to reduce systematic lossage, as well as     * to incorporate impact of the highest bits that would otherwise     * never be used in index calculations because of table bounds.     */    static final int hash(Object key) {        int h;        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);    }

綜合考慮了速度、作用、品質因素,就是把key的hashCode的高16bit和低16bit異或了一下。因為現在大多數的hashCode的分布已經很不錯了,就算是發生了碰撞也用O(logn)的tree去做了。僅僅異或一下,既減少了系統的開銷,也不會造成的因為高位沒有參與下標的計算(table長度比較小時),從而引起的碰撞。再回過頭來看putVal

1.先判斷存有Node數組table是否為null或者大小為0,如果是初始化一個tab並擷取它的長度。resize()後面再說,先看下Node的結構

/**     * Basic hash bin node, used for most entries.  (See below for     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)     */    static class Node<K,V> implements Map.Entry<K,V> {        final int hash;        final K key;        V value;        Node<K,V> next;        Node(int hash, K key, V value, Node<K,V> next) {            this.hash = hash;            this.key = key;            this.value = value;            this.next = next;        }        public final K getKey()        { return key; }        public final V getValue()      { return value; }        public final String toString() { return key + "=" + value; }        public final int hashCode() {            return Objects.hashCode(key) ^ Objects.hashCode(value);        }        public final V setValue(V newValue) {            V oldValue = value;            value = newValue;            return oldValue;        }        public final boolean equals(Object o) {            if (o == this)                return true;            if (o instanceof Map.Entry) {                Map.Entry<?,?> e = (Map.Entry<?,?>)o;                if (Objects.equals(key, e.getKey()) &&                    Objects.equals(value, e.getValue()))                    return true;            }            return false;        }    }


Node實現了鏈表形式,用於儲存hash值沒有發生碰撞的hash、key、value,如果發生碰撞則用TreeNode儲存,繼承自Entry,並最終繼承自Node

/**     * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn     * extends Node) so can be used as extension of either regular or     * linked node.     */    static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {        TreeNode<K,V> parent;  // red-black tree links        TreeNode<K,V> left;        TreeNode<K,V> right;        TreeNode<K,V> prev;    // needed to unlink next upon deletion        boolean red;        TreeNode(int hash, K key, V val, Node<K,V> next) {            super(hash, key, val, next);        }......}


2.以(n - 1) & hash為下標從tab中取出Node,如果不存在,則以hash、Key、value、null為參數new一個Node,儲存到以(n - 1) & hash為下標的tab中

3.如果該下標中有值,也就是Node存在。如果為TreeNode,就用putTreeVal進行樹節點的儲存。否則以鏈表的形式儲存,如果鏈表長度超過8則轉為紅/黑樹狀結構儲存。

4.如果節點已經存在就替換old value(保證key的唯一性)

5.如果bucket(Node數組)滿了(超過load factor*current capacity),就要resize。

總結:put預存程序:將K/V傳給put方法時,它調用hashCode計算hash從而得到Node位置,進一步儲存,HashMap會根據當前Node的佔用情況自動調整容量(超過Load Facotr則resize為原來的2倍)。可見如果不覆蓋hashCode就不能正確的儲存。


3)get擷取
看完put,再看下get
/**     * Returns the value to which the specified key is mapped,     * or {@code null} if this map contains no mapping for the key.     *     * <p>More formally, if this map contains a mapping from a key     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :     * key.equals(k))}, then this method returns {@code v}; otherwise     * it returns {@code null}.  (There can be at most one such mapping.)     *     * <p>A return value of {@code null} does not <i>necessarily</i>     * indicate that the map contains no mapping for the key; it‘s also     * possible that the map explicitly maps the key to {@code null}.     * The {@link #containsKey containsKey} operation may be used to     * distinguish these two cases.     *     * @see #put(Object, Object)     */    public V get(Object key) {        Node<K,V> e;        return (e = getNode(hash(key), key)) == null ? null : e.value;    }

get方法又用到了hash(),是根據key的hash和key擷取Node,返回的值就是Node的value屬性。下面主要看下getNode方法即可
/**     * Implements Map.get and related methods     *     * @param hash hash for key     * @param key the key     * @return the node, or null if none     */    final Node<K,V> getNode(int hash, Object key) {        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;        if ((tab = table) != null && (n = tab.length) > 0 &&            (first = tab[(n - 1) & hash]) != null) {                    //map中存在的情況,不存在則直接返回null            if (first.hash == hash && // always check first node                ((k = first.key) == key || (key != null && key.equals(k))))     //第一個直接命中                return first;            if ((e = first.next) != null) {                             //如果第一個沒命中,擷取下一個節點                if (first instanceof TreeNode)                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);   //如果下一個節點是TreeNode,則用getTreeNode當時擷取                do {                    if (e.hash == hash &&                        ((k = e.key) == key || (key != null && key.equals(k))))    //迴圈節點鏈表,直到命中                        return e;                } while ((e = e.next) != null);            }        }        return null;    }

1)第一個直接命中2)否則,擷取下一個節點,如果是紅/黑樹狀結構,則從紅/黑樹狀結構中擷取,否則迴圈節點鏈表,直至命中。命中的條件是hash相等且key也相同(基本類型==,自訂類則用equals)。
總結:擷取對象時,我們將K傳給get,它調用hashCode計算hash從而得到Node位置,並進一步調用==或equals()方法確定索引值對。可見為了正確的擷取,要覆蓋hashCode和equals方法
題外話:當鏈表長度超過8的時候,java8用紅/黑樹狀結構代替了鏈表,目的是提高效能,這裡不展開。HashMap是基於Map介面的實現,儲存索引值對時,它可以接收null的索引值,是非同步的,HashMap儲存著Entry(hash, key, value, next)對象。
3、為什麼覆蓋equals的時候要覆蓋hashCode通過HashMap的實現原理,可以看出當自訂類作為key值存在的時候一定要這樣做,但不作為key值可以選擇不這樣做(但為了規範起見,還是要覆蓋,因此就變成了必須的了)。如果將測試代碼中的equals或hashCode注釋掉都不能得到正確的結果:
public class PhoneNumber {    private int areaCode;    private int prefix;    private int lineNumber;    public PhoneNumber(int areaCode, int prefix, int lineNumber) {        this.areaCode = areaCode;        this.prefix = prefix;        this.lineNumber = lineNumber;    }//    @Override//    public boolean equals(Object o) {//        if (this == o) return true;//        if (o == null || getClass() != o.getClass()) return false;////        PhoneNumber that = (PhoneNumber) o;////        if (areaCode != that.areaCode) return false;//        if (prefix != that.prefix) return false;//        return lineNumber == that.lineNumber;//    }    @Override    public int hashCode() {        int result = areaCode;        result = 31 * result + prefix;        result = 31 * result + lineNumber;        return result;    }    public static void main(String[] args){        Map<PhoneNumber,String> phoneNumberStringMap = new HashMap<PhoneNumber,String>();        phoneNumberStringMap.put(new PhoneNumber(123, 456, 7890), "honghailiang");        System.out.println(phoneNumberStringMap.get(new PhoneNumber(123, 456, 7890)));    }}
上述結果均為null;

題外話Java中的基本類型可以作為key值,包括String類,String類已經覆蓋了equals方法和hashCode方法。????

【Java實戰】源碼解析為什麼覆蓋equals方法時總要覆蓋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.