4. Java8 Map集合基础知识点

时间:2019-03-19
本文章向大家介绍4. Java8 Map集合基础知识点,主要包括4. Java8 Map集合基础知识点使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Map:

Map集合:

子接口:BindingsConcurrentMap<K,V>, ConcurrentNavigableMap<K,V>, LogicalMessageContextMessageContext

NavigableMap<K,V>, SOAPMessageContextSortedMap<K,V>

实现类:AbstractMapAttributesAuthProviderConcurrentHashMapConcurrentSkipListMapEnumMapHashMap

HashtableIdentityHashMapLinkedHashMapPrinterStateReasonsPropertiesProviderRenderingHints

SimpleBindingsTabularDataSupportTreeMapUIDefaultsWeakHashMap

实现类及子接口较多不一一列举。

1.AbstractMap: 这个类提供了Map接口的框架实现,以最小化实现该接口所需的工作量。为其他的实现类提供基础功能。

2.Attributes: 实现Map接口,内部用HashMap实现,等于把Manifest的各属性转为HashMap保存起来。

3.HashMap:基于哈希表的Map接口的实现类,底层数据结构是由数组+链表+红黑树实现。由源码可得,默认初始容量为16,阈值为0.75,当容量达到阈值之后将会进行扩容。

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

添加元素(源码)put(): 

/**
     * 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;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;    //①,如果是空的数组则,初始化数组容量16,阈值12.
        if ((p = tab[i = (n - 1) & hash]) == null)    
        //"i = (n - 1) & hash"根据key的hash值计算该元素在数组中的索引,
        //i=15&hash ,15与hash值按位与,得到的值处于0-15之间,处于数组的范围之类,同理,不管n多大,该方法算出来的索引值永远不会越界,p = 索引所对应元素
            tab[i] = newNode(hash, key, value, null);    //如果不存在直接创建新节点放进数组。
        else {    //索引所对应元素不为空,p != null
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))    //若原来数组已存在同样的Key值
                e = p;
            else if (p instanceof TreeNode)    //若索引所在节点是树节点
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);    //新建树节点
            else {
                for (int binCount = 0; ; ++binCount) {    //这里循环匹配p节点(链表的头结点)下的各元素,直到匹配上或者到p链表的尾端(即 p.next == null)
                    if ((e = p.next) == null) {    //若索引所在节点的下一节点为空,e = p.next
                        p.next = newNode(hash, key, value, null);    //直接把新key-value对放在p节点下
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st    //③,如果p链表下的元素达到阈值,则把p链表转换为红黑树结构
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))    //若e的key值==新key-value对的key,结束循环。
                        break;
                    p = e;    //p指针后移
                }
            }
            if (e != null) {    // existing mapping for key,存在同样的key值,则替换value
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;    //替换value
                afterNodeAccess(e);
                return oldValue;    //返回旧值
            }
        }
        ++modCount;
        if (++size > threshold)    //如果数组的大小超过阈值,则resize()
            resize();   //②
        afterNodeInsertion(evict);    //后续处理
        return null;
    }

 

Node[] table扩容:resize():在新增key-value对时有两个地方可能触发:

①插入数据前,若数组未初始化则触发扩容函数

if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;    //如果是空的数组则,初始化数组容量16,阈值12.

②插入数据后,根据HashMap中元素个数(size)>阈值(threshold)时触发扩容函数

if (++size > threshold)
            resize();

由源码可得:若数组没有初始化,则初始化数组,初始容量为16,阈值12。若数组已经初始化过,则每次扩容为原来的2倍。

/**
     * 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;
        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
            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 { // 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;
    }

链表转换为红黑树:

③触发条件为:若链表p中的元素个数超过阈值时触发,调用treeifyBin()方法。

treeifyBin方法:数组容量需超过最小树转换容量64。若没有超过则会执行扩容,而不是生成红黑树。

​
 /**
     * Replaces all linked nodes in bin at index for given hash unless
     * table is too small, in which case resizes instead.
     */
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) //①数组长度需超过最小树转换容量
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null);
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            if ((tab[index] = hd) != null)
                hd.treeify(tab);    //转换红黑树
        }
    }

​

其他的关于HashMap操作,像get,remove就不详细说明。大体是根据传进来的参数,用"(n-1)&hash"定位到数组索引。然后根据该索引对应节点的类型进行查找(树类型、或者链表类型)。

 

4. HashTable: Hashtable和HashMap从存储结构和实现来讲有很多相似之处,不同的是它承自Dictionary类,而且是线程安全的,另外Hashtable不允许key和value为null。并发性不如ConcurrentHashMap,因为ConcurrentHashMap引入了分段锁。Hashtable不建议在新代码中使用,不需要线程安全的场合可以使用HashMap,需要线程安全的场合可以使用ConcurrentHashMap。基本弃用,不做详细介绍。

 

5. LinkedHashMap:集成HashMap,大体实现都和HashMap差不多,底层结构是把HashMap的Node数据节点改为双向链表.

6. TreeMap: 基于NavigableMap实现的红黑树。时间复杂度为log(n), 非线程安全。

7.WeakHashMap: 当里面数据节点不再使用时,会自动remove回收。和HashMap类型,默认初始化容量为16,负载因子为0.75f。非线程安全。和HashMap不一样的是,WeakHashMap额外维护一个保存需清除的元素的队列ReferenceQueue

    /**
     * Constructs a new, empty <tt>WeakHashMap</tt> with the default initial
     * capacity (16) and load factor (0.75).
     */
    public WeakHashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }

 其中get()/put(),方法的实现都和HashMap基本相同,不同的是在执行这行操作的时候会额外执行expungeStaleEntries();

该函数目的是从表格中删除过时的条目:遍历table中的元素,然后和ReferenceQueue中的做匹配,匹配上则把value设置为null,这样GC就会回收掉这个元素。

    /**
     * Expunges stale entries from the table.
     */
    private void expungeStaleEntries() {
        for (Object x; (x = queue.poll()) != null; ) {
            synchronized (queue) {
                @SuppressWarnings("unchecked")
                    Entry<K,V> e = (Entry<K,V>) x;
                int i = indexFor(e.hash, table.length);

                Entry<K,V> prev = table[i];
                Entry<K,V> p = prev;
                while (p != null) {
                    Entry<K,V> next = p.next;
                    if (p == e) {
                        if (prev == e)
                            table[i] = next;
                        else
                            prev.next = next;
                        // Must not null out e.next;
                        // stale entries may be in use by a HashIterator
                        e.value = null; // Help GC
                        size--;
                        break;
                    }
                    prev = p;
                    p = next;
                }
            }
        }
    }