【JDK1.8集合】之HashMap

HashMap:

 

成员变量:

//初始容量16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

   //最大容量2^30
    static final int MAXIMUM_CAPACITY = 1 << 30;

//默认填充因子,
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

//Entry链表最大长度,大于该长度,将链表转化为红黑树存储(JDK1.8新增)
    static final int TREEIFY_THRESHOLD = 8;

 //Entry链表小于该长度,将红黑树转化为链表(JDK1.8新增)
    static final int UNTREEIFY_THRESHOLD = 6;

  //转化为红黑树对应的table的最小大小
    static final int MIN_TREEIFY_CAPACITY = 64;

 //存储元素的数组,总是2的幂
    transient Node<K,V>[] table;


 //存放具体元素的Set
    transient Set<Map.Entry<K,V>> entrySet;

 //记录HashMap发生结构性变化的次数(value覆盖不属于结构性变化)
    transient int modCount;

  //扩容的时候下一个table大小的值,(table.length * load factor)
    //size大于这个值会进行resize()扩容
    int threshold;

   //记录HashMap装载因子
    final float loadFactor;

 

构造函数:

 //无参构造,参数均为默认值
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

  //指定初始容量的构造方法,装载因子为0.75
    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;
        //保证initialCapacity的值总为2的幂,tableSizeFor方法返回大于initialCapacity的最小二次幂
        this.threshold = tableSizeFor(initialCapacity);
    }

//指定Map的构造
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }


//将指定Map中的元素插入到HashMap中,
    //evict为false,代表是在创建HashMap时调用这个函数
    //evict为true,代表是在创建HashMap后才调用这个函数
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            //该方法如果是在创建HashMap时,table为null的
            if (table == null) { // pre-size
                //根据指定map的size计算需要创建的HashMap的容量
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                        (int)ft : MAXIMUM_CAPACITY);
                //
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            //如果指定map的size大于threadshold,需要进行resize()
            else if (s > threshold)
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                //
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

 

添加元素:

 

 //put方法,如果key存在,新value替换原来存在的value
    //将key做了一次hash,得到hash值
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

//putIfAbsent与put方法都调用putVal,唯一区别是,第三个参数,一个是false,一个是true,如果为true,不改变已经存在的key。
public V putIfAbsent(K key, V value) {
        return putVal(hash(key), key, value, true, true);
    }

    //onlyIfAbsent 如果为true,不改变已经存在的key。
    //evict 如果false,table处于creation mode。
    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) {
            //如果table为空,需要初始化
            n = (tab = resize()).length;
        }
        //根据hash值确定节点在数组中插入的位置,如果该位置没有元素则插入
        //因为n总是2的幂,i=hash%n
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        //如果该位置有元素
        else {
            Node<K,V> e; K k;
            //比较旧元素和待插入元素的hash值和key值
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //如果旧元素是红黑树节点,调用putTreeVal()
            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);
                        //如果链表节点超过TREEIFY_THRESHOLD - 1,链表转化为红黑树
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //如果链表中节点的key值与插入元素的key值相等则break
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    //用来遍历链表,和e=p.next组合
                    p = e;
                }
            }
            //在数组中找到key,hash与待插入元素相等的节点
            if (e != null) { // existing mapping for key
                //记录e的value
                V oldValue = e.value;
                //onlyIfAbsent为false或者旧值为null
                if (!onlyIfAbsent || oldValue == null)
                    //新值替换
                    e.value = value;
                //访问后回调
                afterNodeAccess(e);
                //
                return oldValue;
            }
        }
        ++modCount;
        //实际大小大于threshold,扩容
        if (++size > threshold)
            resize();
        //插入后回调
        afterNodeInsertion(evict);
        return null;
    }

 //初始化,或者扩容的方法,
    final Node<K,V>[] resize() {
        //记录下旧的table
        Node<K,V>[] oldTab = table;
        //如果旧的table为空,oldCap为0,不为空,oldCap为旧table的大小
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        //记录旧的扩容值,默认0
        int oldThr = threshold;
        //定义了newCap,newThr为0
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                //oldCap比最大容量大,threshold为int最大值
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //如果当前容量小于最大容量,并且扩容过或者准备扩容,那么newThr翻一倍。
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                    oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1;
        }
        //如果oldThr大于0,oldThr就是newCap的大小
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {
            //如果oldCap和oldThr都为0,就会在这里赋值newCap为16,newThr为12
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        //如果新的阀值为0,需要计算新的阀值
        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) {
            //将oldTab中的节点reHash到newTab里面
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    //如果节点是单个节点,则直接在newTab里面进行重定位
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    //如果节点是TreeNode节点,要进行红黑树的rehash操作
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    //如果是链表,进行链表的rehash操作
                    else { // preserve order
                        //一个桶中有多个元素,遍历将它们移到新的bucket或者不改变
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            //根据e.hash&oldCap 判断节点位置rehash后是否发生改变
                            if ((e.hash & oldCap) == 0) {//不改变
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            //放到新的bucket
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            //rehash后新节点的位置为原来基础上加上oldCap
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }



 //hash冲突的情况:
        //1.两节点key值相同,则hash值相同,冲突
        //2.两节点key值不同,hash值相同,冲突
        //3.两节点key值不同,hash不同,在对数组取模后相同,冲突
        final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                                       int h, K k, V v) {
            Class<?> kc = null;
            boolean searched = false;
            TreeNode<K,V> root = (parent != null) ? root() : this;
            //从根节点开始查找合适的位置
            for (TreeNode<K,V> p = root;;) {
                int dir, ph; K pk;
                if ((ph = p.hash) > h)
                    //dir小于0,查找当前节点的左子节点
                    dir = -1;
                else if (ph < h)
                    //dir大于0,查找当前节点的右子节点
                    dir = 1;
                //如果hash值相同,key相同
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                //当前节点与待插入节点key不同,hash值相同
                //k没有实现Comparable接口
                //pk为空,或者k.compareTo(pk)返回值为0
                else if ((kc == null &&
                        (kc = comparableClassFor(k)) == null) ||
                        (dir = compareComparables(kc, k, pk)) == 0) {
                    //
                    if (!searched) {
                        TreeNode<K,V> q, ch;
                        searched = true;
                        if (((ch = p.left) != null &&
                                (q = ch.find(h, k, kc)) != null) ||
                                ((ch = p.right) != null &&
                                        (q = ch.find(h, k, kc)) != null))
                            return q;
                    }
                    //如果k不可比较,走这里进行比较
                    dir = tieBreakOrder(k, pk);
                }
                //xp记录当前节点父节点
                TreeNode<K,V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    //找到待插入的位置
                    Node<K,V> xpn = xp.next;
                    TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
                    if (dir <= 0)
                        xp.left = x;
                    else
                        xp.right = x;
                    xp.next = x;
                    x.parent = x.prev = xp;
                    if (xpn != null)
                        ((TreeNode<K,V>)xpn).prev = x;
                    //插入后,要进行树的平衡
                    moveRootToFront(tab, balanceInsertion(root, x));
                    return null;
                }
            }
        }

final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        //如果tab=null或者tab的长度小于MIN_TREEIFY_CAPACITY(64) 进行扩容
        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);
        }
    }

 

 //调用putMapEntries
    public void putAll(Map<? extends K, ? extends V> m) {
        putMapEntries(m, true);
    }

 

获取元素:

 

 //根据key获取元素
    public V get(Object key) {
        Node<K,V> e;
        //对key进行hash后,根据hash值和key进行查找
        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&(n-1) 得到元素的保存位置
        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;
            if ((e = first.next) != null) {
                //如果是红黑树
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    //如果是链表
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }


//从根节点开始查找
        final TreeNode<K,V> getTreeNode(int h, Object k) {
            return ((parent != null) ? root() : this).find(h, k, null);
        }

 

删除元素:

 

//删除指定key对应的节点,并返回该节点的value
    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
                null : e.value;
    }


final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        //table不为null,长度大于0,并且key的hash值在table里面对应的元素不为null
        if ((tab = table) != null && (n = tab.length) > 0 &&
                (p = tab[index = (n - 1) & hash]) != null) {
            Node<K,V> node = null, e; K k; V v;
            //检查第一个节点,
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            else if ((e = p.next) != null) {
                //如果节点为树
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                    do {
                        if (e.hash == hash &&
                                ((k = e.key) == key ||
                                        (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            if (node != null && (!matchValue || (v = node.value) == value ||
                    (value != null && value.equals(v)))) {
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)
                    tab[index] = node.next;
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

 

posted @ 2017-10-23 21:47  emoji的博客  阅读(247)  评论(0)    收藏  举报