首页 > 其他 > 详细

JDK1.8集合之HashMap

时间:2018-02-21 22:56:11      阅读:252      评论:0      收藏:0      [点我收藏+]

[TOC]

简介

它根据键的hashCode值存储数据,大多数情况下可以直接定位到它的值,因而具有很快的访问速度,但遍历顺序却是不确定的。 HashMap最多只允许一条记录的键为null,允许多条记录的值为null。HashMap非线程安全,即任一时刻可以有多个线程同时写HashMap,可能会导致数据的不一致。如果需要满足线程安全,可以用Collections的synchronizedMap方法使HashMap具有线程安全的能力,或者使用ConcurrentHashMap。

内部实现

HashMap使用了数组来存储值,当发生冲突的时候,使用链表+红黑树(红黑树是JDK1.8新特性)来处理冲突。

技术分享图片

类的属性

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
    // 序列号
    private static final long serialVersionUID = 362498820763181265L;  
    
    // 默认的初始容量是16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;   
    
    // 最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30; 
    
    // 默认的填充因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    
    // 当桶(bucket)上的结点数大于这个值时会转成红黑树
    static final int TREEIFY_THRESHOLD = 8; 
    
    // 当桶(bucket)上的结点数小于这个值时树转链表
    static final int UNTREEIFY_THRESHOLD = 6;
    
    // 桶中结构转化为红黑树对应的table的最小大小
    static final int MIN_TREEIFY_CAPACITY = 64;
    
    // 存储元素的数组,总是2的幂次倍
    transient Node<k,v>[] table; 
    
    // 存放具体元素的集
    transient Set<map.entry<k,v>> entrySet;
    
    // 存放元素(键值对)的个数,注意这个不等于数组的长度。
    transient int size;
    
    // 每次扩容和更改map结构的计数器
    transient int modCount;   
    
    // 临界值 当实际大小(table[].length容量*loadFactor填充因子)超过临界值时,会进行扩容,扩容后的HashMap容量是之前容量的两倍。
    int threshold;
    
    // 填充因子
    final float loadFactor;
}

Node数组

HashMap中的桶数组就是使用Node类来实现的,Node类实现了Map.Entry接口,本质上就是一个键值对。

transient Node<K,V>[] table;

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;
    }
}

重要方法

put()和putVal()方法

put()调用了putVal(),因此重要操作都在putVal()当中。

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

putVal()作用是将新的键值对插入到table中。

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    HashMap.Node<K,V>[] tab; HashMap.Node<K,V> p; int n, i;
    // 如果为空就要进行扩容
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    // (n-1)&hash 是确定放在哪个bucket中
    // 如果元素的计算hash后的位置在table中的bucket暂时没有元素,
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        HashMap.Node<K,V> e; K k;
        // 如果table[hash]的key就是传入的key,那么可以直接覆盖,不用到树或者链表中找
        if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        else if (p instanceof HashMap.TreeNode)
            // 如果结点采用红黑树处理冲突
            e = ((HashMap.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);
                    // 如果链表长度大于转化为红黑树的阈值就要变为树
                    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;
            }
        }
        // 如果能在hashmap中找到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;
}

get()和getNode()方法

get()与getNode()的关系与put()和putVal()关系类似。

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

getNode()

final HashMap.Node<K,V> getNode(int hash, Object key) {
    HashMap.Node<K,V>[] tab; HashMap.Node<K,V> first, e; int n; K k;
    if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
        // 如果bucket的第一个key就是要找的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 HashMap.TreeNode)
                return ((HashMap.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;
}

resize()方法

resize()的作用是table[]达到阈值后就要扩容,返回新的table[]。

这里如果原数组的某个bucket是用链表来处理冲突,那么因为容量和扩容都是2的幂,因此有些优化,在后面提到。

final HashMap.Node<K,V>[] resize() {
    HashMap.Node<K,V>[] oldTab = table;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    int newCap, newThr = 0;
    if (oldCap > 0) {
        // 如果之前table大小达到最大容量上限(1<<30)
        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
        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"})
    HashMap.Node<K,V>[] newTab = (HashMap.Node<K,V>[])new HashMap.Node[newCap];
    table = newTab;

    // 原来的table[]不为空,就进行复制
    if (oldTab != null) {
        // 遍历bucket
        for (int j = 0; j < oldCap; ++j) {
            HashMap.Node<K,V> e;
            // 如果bucket不为空
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                // 如果只有一个元素,直接放入
                if (e.next == null)
                    newTab[e.hash & (newCap - 1)] = e;
                // 否则是树实现
                else if (e instanceof HashMap.TreeNode)
                    ((HashMap.TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                // 是链表实现
                else { // preserve order
                    // 这里与容量和扩容都为2的幂有关,在后面讲
                    HashMap.Node<K,V> loHead = null, loTail = null;
                    HashMap.Node<K,V> hiHead = null, hiTail = null;
                    HashMap.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;
}

容量设置为2的幂的优点

计算Hash时候

方法一:
static final int hash(Object key) {   //jdk1.8 & jdk1.7
     int h;
     // h = key.hashCode() 为第一步 取hashCode值
     // h ^ (h >>> 16)  为第二步 高位参与运算
     return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
方法二:
static int indexFor(int h, int length) {  //jdk1.7的源码,jdk1.8没有这个方法,但是实现原理一样的
     return h & (length-1);  //第三步 取模运算
}

在计算hash的时候,因为n为2的幂,因此可以使用 hashPostion = hash & (n-1) 来代替取模运算,可以加快计算速度。

技术分享图片

扩容时候

扩容的时候,扩容也是原容量乘二,这样可以省去重新计算hash的时间,因为元素的位置要么是在原位置,要么是在原位置再移动2次幂的位置。这里将原来的size为2扩容为4.
技术分享图片

技术分享图片

技术分享图片

这样只需要看原来的hash在扩容后的那一位是1还是0就可以得到新的hash值了。是1的话newHash = oldHash + oldCap(扩容前的容量) / 2

至于扩容后的那一位是1还是0完全是随机的,因此可以看作概率相等,所以这样之后新的桶数组(bucket)的原来那个位置有一半的结点会分到新的位置。

技术分享图片

这里用源码中扩容时候链表的修改做例子。

HashMap.Node<K,V> loHead = null, loTail = null;
HashMap.Node<K,V> hiHead = null, hiTail = null;
HashMap.Node<K,V> next;
do {
    next = e.next;
    // 如果扩容后的那一位是0,说明位置没有改变
    if ((e.hash & oldCap) == 0) {
        if (loTail == null)
            loHead = e;
        else
            loTail.next = e;
        loTail = e;
    } // 否则是改变了,会最后放到原位置+oldCap的位置
    else {
        if (hiTail == null)
            hiHead = e;
        else
            hiTail.next = e;
        hiTail = e;
    }
} while ((e = next) != null);

// 原索引放到bucket里
if (loTail != null) {
    loTail.next = null;
    newTab[j] = loHead;
}

// 原索引+oldCap放到bucket里
if (hiTail != null) {
    hiTail.next = null;
    newTab[j + oldCap] = hiHead;
}

总结

  1. HashMap为线程不安全的,要线程安全需要使用ConcurrentHashMap。
  2. JDK1.8引入了红黑树会使得链表长度过长后,找元素需要的O(n)时间缩短为O(logn)。

参考:http://www.importnew.com/20386.html

JDK1.8集合之HashMap

原文:https://www.cnblogs.com/fightfordream/p/8457699.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!