HashMap的源码学习以及性能分析

HashMap的源码学习以及性能分析

一)、Map接口的实现类

HashTable、HashMap、LinkedHashMap、TreeMap

二)、HashMap和HashTable的区别

1).HashTable的大部分算法做了同步,线程是安全的,HashMap没有同步,线程不安全。

2).Hashtable不允许key或value使用null值,HashMap可以。

3).两者对key的hash算法和hash值到内存索引的映射方法不同。

三)、HashMap的实现原理

HashMap的底层结构:数组 + 链表 + 红黑树

1).数组:Node<K,V>[]

2).链表:Node<k, v>

 属性:int hash,    K key,     V value,    Node<K, v> next;	    

3).红黑树:TreeNode<k, v> extend Node<k, v>

HashMap的主要属性:

1).阈值:threshold

    threshold = 数组总容量 * 负载因子;

    当HashMap的实际容量超过阈值时会进 扩容。

2).负载因子:loadFactor

loadFactor = 元素个数 / 内部数组总大小;

一般情况下loadFactor为介于0 ~ 1之间的浮点数,决定了HashMap在扩容之前

    内部数组的填充度,保证了HashMap的实际填充率不会超过负载因子。

注:HahMap的初始大小为16, 负载因子为0.75f.

//默认初始化容量
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;
//底层数据结构
transient Node<K,V>[] table;
//阈值 = 数组容量 * 负载因子;控制着map的扩容
int threshold;
//负载因子 = 元素个数 / 数组大小
final float loadFactor;
//数组大小
transient int size;

HashMap的存储流程:

创建一个HashMap对象:

Map<String, String> map = new HashMap();

public HashMap() {
    	//设置负载因子为默认值0.75f
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

往map集合中添加数据map.put() :

步骤:

1). 根据hash算法计算key对应的hash值

2). 第一次添加,使用resize()初始化Node<k,v>[]的大小,容量为16

3).根据hash值,通过内存索引映射算法计算该元素在数组的存储位置index

4).判断是否存在冲突,即判断index上是否有元素存在

5). 若没有重突,直接将元素存储在index位置上

6).若发生了重突,则根据Node<k, v> tab, tab[index].next遍历,将元素添加到数组index上对应的链表的末尾。

7).判断链表的大小是否=8,当链表的长度=8 时,将链表结构的存储转为红黑树结构的存储形式。

8).若发生冲突,数组对应元素的类型为TreeNode<k,v>,使用红黑树的算法添加元素

map.put("a","hhh")

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

static final int hash(Object key) {
        int h;
    	//hashCode()的计算使用native实现,即是由jvm底层来实现
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    
//该方法的定义在Object类中
public native int hashCode();
    }

//添加元素
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)
            //初始化 Node<K,V>[]的大小
            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;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //判断冲突的数组元素的类型是否为TreeNode红黑树类型
            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);
                        //如果链表的长度超过8,则将链表结构转为红黑树机构
                        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;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

//初始化HashMap数组或对数组进行扩容
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) {
            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;
        //第一次使用设置初始容量为16
        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的值
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        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;
                    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;
    }

HashMap的get()原理实现

map.get("a")

步骤:

1).通过hash算法计算key对应的hash值

2).根据hash值,通过内存索引映射算法计算key对应的内部数组角标

3).判断角标下的数组元素next值是否为空

4).若next == null,直接返回角标对应的元素

5).若next 不为空,则遍历角标元素下的链表结构,根据key返回对应的Node<k,v>

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;
        //判断hash映射的数组元素是否有下一个值
        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;
            //如果hash映射的数组元素有下一个值
            if ((e = first.next) != null) {
                //判断数组元素下的数据结构,
                if (first instanceof TreeNode)
                    //数据结构为红黑树,使用红黑树算法查找
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                //数据结构为链表,根据key进行查找
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

结论:

1).只要hashCode()和Hash()方法实现得足够好,能尽可能的减少冲突,对HashMap的操作几乎等价于数组的随机访问操作。

2).如果hashCode()和Hash()方法实现比较差,HashMap的事实就退化为几个链表,对HashMap的操作相当于遍历链表。

四)、HashMap的子类,LinkedHashMap

HashMap的缺点:无序性;在遍历HashMap时输入顺序与输出顺序不同。

LinkedHashMap: 保证了元素的输入顺序与输出顺序一致。

LinkedHashMap保证元素有序的原因:

LinkedHashMap 内部增加了一个链表,继承了HahMap时也继承了HashMap.Entry类,实现LinkedHashMap.Emtry,增加了before和after属性

Entry<k, v> before;

Entry<k, v> after;

 static class Entry<K,V> extends HashMap.Node<K,V> {
        Entry<K,V> before, after;
        Entry(int hash, K key, V value, Node<K,V> next) {
            super(hash, key, value, next);
        }
    }
金麟岂能忍一世平凡 飞上了青天 天下还依然
原文地址:https://www.cnblogs.com/Auge/p/11656119.html