java Map

Map

  HashMap

    jdk1.8 数组+链表+红黑树(Node<K,V>[] table;TreeNode),增删查的效率高;无序的,不可重复的,线程不安全的散列表

    源码分析:(默认容量16,平衡因子0.75,阈值12=容量*平衡因子,所以平衡因子越大,扩容次数少,越小,越易扩容)     

      在插入时进行初始化扩容操作,随机插入数组节点(数组长度与hash值与操作确定 tab[i = (n - 1) & hash]) ,所以map的大小最好为2的n次方,因为2的n次方-1二进制为111,位置则根据hash值确定

      插入时,如果数组当前位置存在数据,则说明存在hash冲突(hash冲突的坏处,越多链表越长,性能越低,空间利用率也低)

        首先判断是否根据当前元素是同一元素(根据当前元素的hash值、key、K.equals()与插入元素比较),相同则新值替换旧值(所以重写equals()方法时需要重写hashcode,避免hash冲突)

        不是同一元素,若当前节点为node链表,插入作为当前节点的尾节点,当链表长度超过8转为红黑树结构

        不是同一元素,若当前节点为TreeNode结构,采用红黑树的插入方法,平衡树结构

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)
            n = (tab = resize()).length;//扩容,初始化
        if ((p = tab[i = (n - 1) & hash]) == null)//随机插入数组,第一个元素在首位
            tab[i] = newNode(hash, key, value, null);
        else {//当前位置存在数据,hash冲突
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;//当前位置的hash值、key与equal()值相同,新值替换旧值
            else if (p instanceof TreeNode)//不是同一个值,是红黑树则维持平衡添加
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {//不是同一个值,增加到链表尾节点,链表长度大于8则转换结构为红黑树
                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;
                }
            }
            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;
    }
插入,进行初始化
      获取值,根据hash值获取数组位置(tab[i = (n - 1) & hash]))
        有值,遍历当前元素,根据key、hash、equal()获取相同元素返回
        无值,返回null
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 = tab[(n - 1) & hash]) != null) {//根据hash值获取数组位置,存在值
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;//确定根节点,根据key、hash、equal()去寻找元素
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {//遍历链表,根据key、hash、equal()去寻找元素
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }
获取值,通过hash值获取

      resize()--扩容(当容量大于阈值进行扩容,容量扩大2倍,阈值扩大2倍)、初始化

      遍历旧数组

        元素不存在链表,根据hash值随机到新数组

        元素存在链表,根据奇偶链表,保证顺序,复制到新节点

        元素存在红黑树链表,复制到新节点

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;
        else {               // 初始化,容量为0
            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];
        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 { // 链表,分成奇偶两条链表,保证顺序移动到新节点
                        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;
    }
View Code          

  ConcurrentHashMap

      线程安全的HashMap,在put操作时使用了synchronized去保证线程安全性;

      主要使用CAS+synchronized来保证线程安全性

      具体可参考:https://www.jianshu.com/p/d0b37b927c48


原文地址:https://www.cnblogs.com/ruerror/p/13636220.html