java集合源码解析:map

map里面用的最多的就是HashMap了, 如果需要对key进行排序的话,会用到 TreeMap

先看看HashMap的源码

HashMap内部还是用数组的方式实现的

transient Node[] table;
//Node的定义,除了key,value外,hash用来确定在数组中的位置. Node数组中每个元素其实是个链表(链表长度超过8则转为红黑树)结构,当有hash冲突时,这个链表中就会存放有相同hash值的节点,
//next用来表示其在链表(红黑树)中的下一个节点
    static class Node implements Map.Entry {
        final int hash;
        final K key;
        V value;
        Node next;

        Node(int hash, K key, V value, Node 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方法添加元素时,需要先根据hashcode确定在数组中的位置,然后找出此位置的节点,然后插入这个节点对应的链表(红黑树)中

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node[] tab; Node p; int n, i;
	//在put时需要先判断map是否为空,如果为空则需要用resize()进行扩容,jdk1.6中会在new HashMap() 时对数组进行初始化,但是jdk1.8中则不会,直接将初始化的操作放在了put方法里面
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
	//这里先根据Node的hash值来计算在数组中的索引"i",如果tab[i]为空则直接插入这个位置
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
	//如果不为空,则说明有了相同的hash值,如果key也相同,那么直接覆盖现有元素,如果没有相同的key,说明hash值有了冲突,需要将这个Node放在此处对应的链表(红黑树)中
        else {
            Node e; K k;
	//有对应的key,直接覆盖
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
	//这个节点已经是红黑树了,直接插入红黑树中
            else if (p instanceof TreeNode)
                e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);
            else {//如果还不是红黑树,那么则是一个链表,遍历链表中的数据,如果有相同的key则替换,没有则放到链表结尾
                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 链表长度超过8,链表转换为红黑树
                            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默认容量为16,默认加载因子为0.75, 当map里面的内容超过容量*加载因子时,就需要对map进行扩容操作,避免产生过多的hash冲突

使用resize()扩容时,会扩容为原来长度的2倍,jdk1.8之前进行扩容需要重新计算整个map的hash值,jdk1.8进行了优化

在resize()的注释中我们可以看到 must either stay at same index, or move with a power of two offset in the new table, 一部分保持原来位置,另一部分则会根据原位置再移动2次幂(比如原来下标是15,总长度是16,现在扩容长度变为32,那么原来15位置的节点,部分不变,另一部分会移动到15+16=31的位置),具体的可以看resize()的代码:

    final Node[] resize() {
        Node[] 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 计算新的容量,左移一位,变为原来长度的2倍
        }
        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[] newTab = (Node[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node 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)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        Node loHead = null, loTail = null;
                        Node hiHead = null, hiTail = null;
                        Node 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时,只需要先根据hash值获取对应的下标,然后遍历对应的链表或者红黑树,找到对应的value即可

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


TreeMap则可以根据key进行排序,每个节点都是一个红黑树,红黑树比一般的二叉搜索树要复杂的多,以后有空再研究下吧
Hashtable跟HashMap的实现基本类似,Hashtable不允许key 为null,而HashMap则可以, Hashtable也是线程安全的,在方法上都加了synchronized

而collection里面的HashSet 和 TreeSet则是直接依赖了HashMap和TreeMap,将map里面的可以作为集合元素(与value无关,value = new Object())

你可能感兴趣的:(JAVA源码分析)