Java HashMap

Java HashMap的那些事情

1、HashMap最前的注释

以hash表为基础的一个Map。这个实现扩展了Map接口的一些操作。并且允许null键与null值。HashMap大概跟Hashtable是一样的,除了HashMap不是同步的且允许null键值。HashMap不保证元素的有序性。

讲了初始化容量与加载因子的一些事。其中容量就是我们常说的Bucket的数量,加载因子决定了这个HashMap有多满。

加载因子缺省为0.75,是一个折中的值。

如果要存储很多的mapping,也就是说map中有很多键值对的时候,应该要指定其大小,避免因为扩容造成很多时间空间浪费。

注意HashMap不是同步的,可以使用Collections.synchronizedMap对Map进行包装使Map同步。

2、具体实现

HashMap的声明:

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable

继承了AbstractMap,实现了Map,Cloneable,Serializable接口。

一些常量:

//默认初始化容量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//默认加载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//当某个桶的entry数量大于8时,会变成红黑树的结构。
static final int TREEIFY_THRESHOLD = 8;
//当桶中的结点小于6的时候,会变成链表的形势
static final int UNTREEIFY_THRESHOLD = 6;
//当hash表的容量大于64的时候才会进行树形化,否则会进行扩容操作,而不是树形化。
static final int MIN_TREEIFY_CAPACITY = 64;

hash算法:

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

可以看到HashMap是允许键为null的,当键为null时hashcode为0。

当键部位null时,hashcode为key的hashcode()异或key的hashcode()无符号右移16位。

hashcode是32位的,无符号右移16位就意思是只剩高位的16位还在,其他位为0。这样做异或可以使得在计算hashcode的时候高低位都会被照顾到,这样应该是有助于让hash的值分开的比较广。也就是差异性比较大。

/**
     * Returns a power of two size for the given target capacity.
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

这里是返回一个距离cap最近的一个二的幂次方。如cap=16,返回16。cap=15,返回16。

为什么cap需要时2的幂次方呢?

这里比较有意思。当我们在计算出来一个键的hashcode之后,一般的做法是我们用hashcode对table length也就是cap取模运算,得到这个键对应的table的位置。比如hashcode=5,table length= 16,此时5%16=5,也就是放在table的第5个位置。但是,计算机取模运算的效率比较低下。这个时候,人们发现如果length是2的幂次方,会发现hashcode % table length = hashcode & (table length - 1),这样可以通过位运算代替取模运算,提高效率,当然前提是table length必须是2的幂次方。

HashMap的put

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
    //首先进行初始化table的长度
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
    //这里进行hash的操作,找元素在table中的位置
    //如果某个位置没有元素则直接创建新的Node并插入
        if ((p = tab[i = (n - 1) & hash]) == null)
            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;
            //如果发现这个要插入的位置的Node是红黑树
            else if (p instanceof TreeNode)
                //直接插入树中
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                //如果不是树,也就是链表,就遍历找位置插入,如果找到有相同的键会覆盖
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //如果链表长度超过7,就变成树结构
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                     //链表中已经存在了,覆盖
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
           
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
    //fail-fast
        ++modCount;
    //如果超过最大容量会进行扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

具体步骤:

①、判断键值对数组 table 是否为空或为null,否则执行resize()进行扩容;

②、根据键值key计算hash值得到插入的数组索引i,如果table[i]==null,直接新建节点添加,转向⑥,如果table[i]不为空,转向③;

③、判断table[i]的首个元素是否和key一样,如果相同直接覆盖value,否则转向④,这里的相同指的是hashCode以及equals;

④、判断table[i] 是否为treeNode,即table[i] 是否是红黑树,如果是红黑树,则直接在树中插入键值对,否则转向⑤;

⑤、遍历table[i],判断链表长度是否大于8,大于8的话把链表转换为红黑树,在红黑树中执行插入操作,否则进行链表的插入操作;遍历过程中若发现key已经存在直接覆盖value即可;

⑥、插入成功后,判断实际存在的键值对数量size是否超过了最大容量threshold,如果超过,进行扩容。

⑦、如果新插入的key不存在,则返回null,如果新插入的key存在,则返回原key对应的value值(注意新插入的value会覆盖原value值)

注意:hashMap的size,如果插入相同的key,size是不会改变的。

扩容操作

final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            //如果以前的容量已经是最大容量,就直接把阈值设为最大
            //因为这里的cap已经最大了,设置thr也没意义了,干脆就直接设置最大
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //如果将以前的容量乘2给新容量之后 < 最大容量 && 以前的容量 >= 初始容量16
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                //thr = cap * load factor
                //newThr * 2 = new Cap * 2 * load factor
                //阈值就扩大一倍
                newThr = oldThr << 1; // double threshold
        }
    //如果以前的阈值大于0,就直接将新的容量设为阈值(因为这里的前提是以前的容量<=0)
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
    //如果阈值也小于等于0,以前的容量也小于等于0
        else {               // zero initial threshold signifies using defaults
            //新的容量设置为缺省的容量,新的阈值设为缺省容量*缺省加载因子
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
    //计算新的阈值上限
        if (newThr == 0) {
            float ft = (float)newCap * 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];
    //因为前面已经将oldTab保存了下来
        table = newTab;
    //如果oldtab不为空
        if (oldTab != null) {
            //遍历以前的table,将值一个个赋给e之后将索引的位置置于null便于GC
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    //数组没有next,说明不是链表,直接插入
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    //在这里如果发现访问的e是树的结点
                    else if (e instanceof TreeNode)
    //Splits nodes in a tree bin into lower and upper tree bins, or untreeifies if now too small. Called only from resize; see above discussion about split bits and indices.
                        ((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;
    }

删除操作

public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }
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;
    //老亚子,table不为空&&table长度大于0&&键存在于table中
        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 {
                    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
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

get与contain操作

public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }


final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    //还是那样,先看table是否为空且查的值是否存在
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != 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);
                do {
                    //遍历链表结点
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

contains操作(同上)

public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }

posted @ 2019-07-10 15:37  GaryZz  阅读(243)  评论(0编辑  收藏  举报