HashMap分析

HashMap源码分析

  • HashMap数据结构  数组+链表

java编程语言中,最基本的结构就是两种,一个是数组,另外一个是模拟指针(引用),所有的数据结构都可以用这两个基本结构来构造的,HashMap也不例外。HashMap实际上是一个链表散列的数据结构,即数组和链表的结合体。

 

  • 成员变量

      // 序列号

    • private static final long serialVersionUID = 362498820763181265L;    

      // 默认的初始容量是16

    • static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;   

      // 最大容量

    • static final int MAXIMUM_CAPACITY = 1 << 30;

      // 默认的填充因子

    • static final float DEFAULT_LOAD_FACTOR = 0.75f;

      // 当桶(bucket)上的结点数大于这个值时会转成红黑树

    • static final int TREEIFY_THRESHOLD = 8;

      // 当桶(bucket)上的结点数小于这个值时树转链表

    • static final int UNTREEIFY_THRESHOLD = 6;

      // 桶中结构转化为红黑树对应的数组的最小大小,如果当前容量小于它,就不会将链表转化为红黑树,而是用resize()代替

    • static final int MIN_TREEIFY_CAPACITY = 64;

      // 存储元素的数组,总是2的幂

    • transient Node<k,v>[] table;

      // 存放具体元素的集

    • transient Set<map.entry<k,v>> entrySet;

      // 存放元素的个数,注意这个不等于数组的长度。

    • transient int size;

      // 每次扩容和更改map结构的计数器

    • transient int modCount;   

      // 临界值 当实际节点个数超过临界值(容量*填充因子)时,会进行扩容

    • int threshold;

      // 填充因子

    • final float loadFactor;

  • put方法源码

 

public V put(K key, V value) {

    // keyhashCode()hash

    return putVal(hash(key), key, value, false, true);

}

 

 

/**

* 用于实现put()方法和其他相关的方法

*

* @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;

    // table未初始化或者长度为0,进行扩容,n为桶的个数

    if ((tab = table) == null || (n = tab.length) == 0)

        n = (tab = resize()).length;

    // (n - 1) & hash 确定元素存放在哪个桶中,桶为空,新生成结点放入桶中(此时,这个结点是放在数组中)

    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,用e来记录

                e = p;

        // hash值不相等或key不相等

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

                    // 结点数量达到阈值,调用treeifyBin()做进一步判断是否转为红黑树

                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st

                        treeifyBin(tab, hash);

                    // 跳出循环

                    break;

                }

                // 判断链表中结点的key值与插入的元素的key值是否相等

                if (e.hash == hash &&

                    ((k = e.key) == key || (key != null && key.equals(k))))

                    // 相等,跳出循环

                    break;

                // 用于遍历桶中的链表,与前面的e = p.next组合,可以遍历链表

                p = e;

            }

        }

        // 表示在桶中找到key值、hash值与插入元素相等的结点

        if (e != null) {

            // 记录evalue

            V oldValue = e.value;

            // onlyIfAbsentfalse或者旧值为null

            if (!onlyIfAbsent || oldValue == null)

                //用新值替换旧值

                e.value = value;

            // 访问后回调

            afterNodeAccess(e);

            // 返回旧值

            return oldValue;

        }

    }

    // 结构性修改

    ++modCount;

    // 实际大小大于阈值则扩容

    if (++size > threshold)

        resize();

    // 插入后回调

    afterNodeInsertion(evict);

    return null;

}

 

//将指定映射的所有映射关系复制到此映射中

public void putAll(Map<? extends K, ? extends V> m) {

    putMapEntries(m, true);

}

 

//m的所有元素存入本HashMap实例中,evictfalse时表示构造初始HashMap

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {

    int s = m.size();

    if (s > 0) {

        // table未初始化

        if (table == null) { // pre-size

            //计算初始容量

            float ft = ((float)s / loadFactor) + 1.0F;

            int t = ((ft < (float)MAXIMUM_CAPACITY) ?

                    (int)ft : MAXIMUM_CAPACITY);

            if (t > threshold)

                threshold = tableSizeFor(t);//同样先保存容量到threshold

        }

        // 已初始化,并且m元素个数大于阈值,进行扩容处理

        else if (s > threshold)

            resize();

        // m中的所有元素添加至HashMap

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

        }

    }

}

 

//将链表转换为红黑树

final void treeifyBin(Node<K,V>[] tab, int hash) {

    int n, index; Node<K,V> e;

    //若数组容量小于MIN_TREEIFY_CAPACITY,不进行转换而是进行resize操作

    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);//Node转换为TreeNode

            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); //重新排序形成红黑树

    }

}

 

  • get方法源码

 

public V get(Object key) {

    Node<K,V> e;

    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;

    // table已经初始化,长度大于0,且根据hash寻找table中的项也不为空

    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;

}

 

 

public boolean containsKey(Object key) {

    return getNode(hash(key), key) != null;

}

 

public boolean containsValue(Object value) {

    Node<K,V>[] tab; V v;

    if ((tab = table) != null && size > 0) {

        //外层循环搜索数组

        for (int i = 0; i < tab.length; ++i) {

            //内层循环搜索链表

            for (Node<K,V> e = tab[i]; e != null; e = e.next) {

                if ((v = e.value) == value ||

                    (value != null && value.equals(v)))

                    return true;

            }

        }

    }

    return false;

}

posted @ 2019-03-22 20:00  Feture  阅读(316)  评论(0)    收藏  举报