JDK中集合源码阅读(持续更新)

原创
2018/04/15 21:29
阅读数 40

环境:JDK8

1. ArrayList

ArrayList底层实现是数组,在新增元素的时候会根据当前数组大小,进行扩容。

先来看几个构造方法

默认构造方法,将内部数组初始化为空数组,可以看DEFAULTCAPACITY_EMPTY_ELEMENTDATA的定义,类型是Object[] 

    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

还可以传入一个数字进去,即初始容量,创建一个该容量的数组,注意类型也是Object类型

    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

 

再来看下平时比较常用的add方法

public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

可以看到,新增元素的时候,首先调用了一个ensureCapacityInternal方法,传入的参数是当前列表的size+1,用于确保内部容量是否够用。继续

private void ensureCapacityInternal(int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }

    ensureExplicitCapacity(minCapacity);
}

可以看到,首先判断了下是否是空数组,如果是的话,在默认容量10和最小容量之间取最大值,作为新的最小容量,继续

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

可以看到,ArrayList记录了每次修改内部数组的次数,modCount,将其加一,然后再次判断,如果最小容量大于内部数组的长度,则调用grow方法,进行扩容

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

grow方法的第三行说明了扩容规则,即 新容量=当前容量+当前容量/2,(增长当前的一半)

后面的判断是防止计算后的大小偏大或偏小。最后一行即进行数组复制操作。

 

2. HashMap

HashMap的底层数据结构是:动态数组+单向链表/红黑树


    /**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     */
    transient Node<K,V>[] table;

    /**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     */
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
    }

默认构造方法,设置默认的加载因子(0.75)

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

和ArrayList一样,也有一个可设置初始容量的构造方法,这里调了另一个构造方法

    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }

注意到最后一行,这里根据初始容量,设置了一个阈值,这个字段的注释是The next size value at which to resize (capacity * load factor). 即下一次resize(扩容)时数组的大小。

    /**
     * Returns a power of two size for the given target capacity.   此处返回的是比cap大的最小的2的幂
     */
    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;
    }

 

继续看向Map中放值得put方法,可以

看到调用了putVal方法,并需要先计算key的hash并将其传入

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

 此处可以看到,哈希的计算方式是 对key的hashcode的低16位与高16位进行异或,高位不变。

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

 下面来看putVal方法(代码见下)。

如果当前容器为空,则会先调用resize方法;

接着来看putVal方法第四行,可以看到,计算当前key的位置的方法:(n - 1) & hash,其中n是内部数组的长度,hash是刚才计算过的,由于hashmap的数组大小永远是2的n次幂,因此这里的效率也比取模快,也能达到分散哈希的目的。

此处判断了下,该槽位上有没有数据。

1)如果没有,则创建一个Node对象

2)如果该key的槽位已经有数据,即可能发生了“哈希碰撞”,说是可能是因为有可能传入的key是重复的。如果是重复的话(即key已经存在,变量e保存),将根据onlyIfAbsent判断是否覆盖当前的值。

如果确实出现“哈希碰撞”的话,则将该key放入链表的末尾。  而为了提高查询效率,当链表长度大于阈值 TREEIFY_THRESHOLD(8) 时,就会转化为红黑树;当小于等于6时,会转回链表。

    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;                     // 判断如果为空,则resize
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);   // 如果该槽位为空,则创建一个新的node
        else {                  // 如果该槽位有值
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;      // 如果key相同,则将e赋值为该node
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);  
            else {  
                // 如果不是tree,则循环链表,添加到尾端
                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;  // 如果key已经存在了,则退出循环,此时e就是当前的node
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;      // 如果onlyIfAbsent为false,才覆盖原值
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();  // 添加后的 数组大小如果超过了阈值,则扩容
        afterNodeInsertion(evict);
        return null;
    }
    Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
        return new Node<>(hash, key, value, next);
    }

 

可以看到,如果容器为空,则会将容量设为默认容量(16),阈值设为 默认容量*默认加载因子=12

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

然后,创建一个Node数组,大小为新容量newCap。

resize方法主要是两部分:计算新的容量和阈值,创建一个新的Node数组,将老的数据移入到其中。

 

看下红黑树的节点定义

    /**
     * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn
     * extends Node) so can be used as extension of either regular or
     * linked node.
     */
    static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red;
    }

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部