HashMap源码注解 之 内部数据结构 Node (三)

注意 , 本文基于JDK 1.8
《HashMap源码注解 之 内部数据结构 Node (三)》

1.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是指key对应的hash值。
其成员方法hashCode为node对象的hash值。
在成员变量table中引用的就是这个Node。

    transient Node<K,V>[] table;

其实在HashMap中大部分用到的是链表存储结构,很少用到树形存储结构。其实,理想情况下,hash函数设计的好,链表存储结构都用不到。
关于HashMap的hash函数的设计请看博文 HashMap源码注解 之 静态工具方法hash()、tableSizeFor()(四)

    原文作者:fan2012huan
    原文地址: https://blog.csdn.net/fan2012huan/article/details/51097264
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞