jdk源码阅读之HashMap(一)

HashMap是一个散列表,这个散列表包含的散列桶的格式为2^n个,而且必须满足这个条件,原因在getNode(int hash, Object key)这个方法的分析中给出。HashMap允许null的键值对,null的键值对总会被映射到第一个散列桶中。HashMap里面的键值对并没有顺序之分,里面的结构是使用数组+链表或者是红黑树,是否将链表变成红黑树的条件是,一个桶里面节点的个数大于MIN_TREEIFY_CAPACITY

static final int MIN_TREEIFY_CAPACITY = 64;

HashMap的容量是指散列桶的个数,在构造函数中传入,如果构造时传入的参数不满足这个条件,内部会做相应的调整,以满足,HashMap的构造函数如下:

public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }
public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }
public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

默认的HashMap大小为16

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

HashMap是一个散列表,散列表的节点是Node这个类

//Node实现了Map类里面的Entry接口
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; }
		/* 节点的哈希码,注意这个并不是用来定位key的位置的哈希码方法,
		* 获得key的哈希码的方法是HashMap.hash方法,使用这个哈希码来决
		* 定该key存放在哪个散列桶内
		*/
        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) {
        //相等的依据是两者引用相等,或者两者的key、value分别相等
            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;
        }
    }

每个节点的哈希码是以key的哈希码来计算的,具体计算方式如下:

static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

从上面的哈希码计算方式可知
1.如果key为null,则哈希码为0,因为HashMap的键值对可以为null-null,因此,key为null的节点都会被映射到第一个散列桶里面。
2.如果key不为null,则调用key的哈希码生成方法,则返回key本身的哈希码异或高16位,这样做的原因是当散列表比较小的时候,让高位一块进行运算,更能有效的防止大多数节点映射到同一个散列桶.

解决了哈希码的生成之后,如何将哈希码和存储位置联系起来呢?让我们先看一下获取节点的方法

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代表的是散列桶的第一个节点,从获取节点的方式可以知道,散列桶的位置
        其实就是节点的哈希码位与散列桶个数-1,**(注意一个桶里面的key的哈希码并不一样)**,为什么要与上散列桶个数-1,原因在于
        散列桶的个数为2^n,即1<<n,(1<<n)-1可以保证低位全部为1,这样的话,也不会
        造成数组的越界,我想这也应该是散列桶个数为什么必须是2^n个的原因
        */
            (first = tab[(n - 1) & hash]) != null) {
            //首先检查第一个节点是否满足要求,碰到一个key相等的,即返回这个节点
            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);
                do {
                //遍历这个散列桶,知道获取到正确的节点,否则返回null
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;

put操作

put操作是向HashMap添加一个键值对,如果该键已经存在,则更新旧的值

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
/**
     * 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;
        //如果HashMap里面还没有任何键值对,则进行resize操作进行扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //如果该键值对映射的散列桶还没有任何元素,则直接映射到该散列桶
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
        //散列桶存在元素
            Node<K,V> e; K k;
            //检查第一个,如果第一个节点的key已经和需要插入的key相同,则e=p
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
            //如果p为红黑树的节点,这里是为了提高查找性能,当节点冲突太高的时候,使用红黑树而不是链表,运行完这一句,e仍然指向需要更新的节点或者null.
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
            //既不是散列桶的第一个,又不是红黑树,则遍历链表
            //下面的for循环只是象征性的,因为不知道链表里面元素的个数,当满足一定条件就break
                for (int binCount = 0; ; ++binCount) {
                //已经遍历到链表尾,说明没有相同的key存在,则插入新的节点
                    if ((e = p.next) == null) {
                    //插入新的节点,这时,e引用的是新节点
                        p.next = newNode(hash, key, value, null);
                        //将链表转化成红黑树
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //如果找到相同的key节点,e引用这个节点
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //如果运行到这里,那么e已经是引用了新的节点,或者旧的相同key的节点
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

resize操作

/**
 * Initializes or doubles table size.  If null, allocates in
 * accord with initial capacity target held in field threshold.
 * Otherwise, because we are using power-of-two expansion, the
 * elements from each bin must either stay at same index, or move
 * with a power of two offset in the new table.
 *
 * @return the table
 */
final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;
    //oldTab为null的时候,散列桶里面没有任何元素
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    int newCap, newThr = 0;
    if (oldCap > 0) {
    	//如果旧的容量为最大容量的话,那么就不能扩容,直接返回
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
              //满足条件,就扩容
            newThr = oldThr << 1; // double threshold
    }
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    else {               // zero initial threshold signifies using defaults
    	//旧的容量为0
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    if (newThr == 0) {
        float ft = (float)newCap * loadFactor;
        //threshold=capacity*loadfactor
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }
    threshold = newThr;
    @SuppressWarnings({"rawtypes","unchecked"})
    //创建新的散列表
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
    //如果旧的table不为空,则重新散列
    if (oldTab != null) {
    //遍历所有的散列桶
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
            //当前散列桶不为空
                oldTab[j] = null;
                if (e.next == null)
                //当前散列桶只有一个节点,则把这个节点重新散列即可
                    newTab[e.hash & (newCap - 1)] = e;
                 //如果e是红黑树节点的话,就要遍历红黑树重新散列
                else if (e instanceof TreeNode)
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                else { // preserve order
                    Node<K,V> loHead = null, loTail = null;
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    //下面是对旧的散列桶进行重新散列,具体说明见下面详细说明
                    do {
                        next = e.next;
                        if ((e.hash & oldCap) == 0) {
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
                        else {
                            if (hiTail == null)
                                hiHead = e;
                            else
                                hiTail.next = e;
                            hiTail = e;
                        }
                    } while ((e = next) != null);
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}

对于上面旧散列桶中元素重新散列的部分,进行说明,因为代码比较难懂,首先要声明的是旧的一个散列桶中的元素重新散列的可能只有两种:
假如旧散列桶个数oldCap为2^5=32个,那么table的寻址范围为:0~31,对第20个散列桶中的元素进行分析,哈希码位h,那么先来看h的可能取值:
h^(32-1)=20 二进制表示:h ^ 11111=10100
可以得出h的可能:xxx10100
现在重新散列,散列桶个数翻倍newCap=2^6=64,散列桶的位置:
z=h^(64-1)=xxx10100 ^ 111111=x10100 ^ 111111
当x为1时:z=10100,重新散列在原位置
当x=0时,z=110100=10100+100000=10100+oldCap,重新散列在20+oldCap这个位置,对应代码:

newTab[j + oldCap] = hiHead;

这样上面的代码就好理解了,再解释这几个变量

Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;

loHead 、loTail 分别代表旧散列桶重新散列之后,仍然待在旧的散列桶的元素组成的链表首尾;相应的hiHead 、hiTail 分别代表旧散列桶重新散列之后,被映射到新的散列桶的元素组成的链表首尾.

remove操作

public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }
 /**
     * Implements Map.remove and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to match if matchValue, else ignored
     * @param matchValue if true only remove if value is equal
     * @param movable if false do not move other nodes while removing
     * @return the node, or null if none
     */
    final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            Node<K,V> node = null, e; K k; V v;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                //第一个就是需要删除的节点
                node = p;
            else if ((e = p.next) != null) {
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                	//遍历当前散列桶所有的节点,退出时总是有e=p.next,node=e,e指向需要删除的节点
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)
                	//根据上面的关系,说明需要删除的节点是第一个
                    tab[index] = node.next;
                else
                	//根据上面的关系,node为需删除的节点,去掉其引用,由垃圾回收器回收
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

关于HashMap还有一个很重要的操作,就是遍历,这一部分放到另一篇

猜你喜欢

转载自blog.csdn.net/whoami_I/article/details/86165391