简单看懂HashMap1.8源码

HashMap1.8跟之前相比增加了红黑树的数据结构。
Hashmap1.8的数据结构为数组+链表+红黑树。

数据结构:

        


源码:
一点一点分析:
先看HashMap源码中定义的几个重要属性:
先不管他们是干嘛的!只看注释的意义!

    /**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

默认的初始化容量,也就是数组初始化长度 2^4 = 16

    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;


HashMap的最大长度 2^30 

    /**
     * The next size value at which to resize (capacity * load factor).
     *
     * @serial
     */
    // (The javadoc description is true upon serialization.
    // Additionally, if the table array has not been allocated, this
    // field holds the initial array capacity, or zero signifying
    // DEFAULT_INITIAL_CAPACITY.)
    int threshold;
    /**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

这个参数的意义是:当数组长度达到当前长度 * 0.75时 需要扩容了!
threshold = capacity * load factor

    /**
     * The bin count threshold for using a tree rather than list for a
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes. The value must be greater
     * than 2 and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     */
    static final int TREEIFY_THRESHOLD = 8;

!!!太长了看不懂,第一句的意思大概是超过这个值就转换为树结构!

    /**
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     */
    static final int UNTREEIFY_THRESHOLD = 6;

大概的意思是二叉树长度小于这个值就会重置
===============================================
HashMap里元素的基本数据结构--Node


hash 是这个Node的key的hash值  next是指向的下一个Node


这个数组就是HashMap的最基本的数组 所有的元素计算key的hash,然后同样的放在一个数组元素的下方用指针指向下一个。

=========================================
下面粗糙的说一下HashMap的put()方法的原理,各位老师可以照比研究一下,说的不对,接受批评。

调用put()方法的时候会调用putVal()方法,参数有五个,有用的有前3个。

/**
 * 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;
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        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);
                    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;
                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在put的时候会先判断当前HashMap的数组,如果为空则新建一个:然后分两种情况:
1:若不为空则用当前数组的长度-1 与put的元素的key的hash值进行与运算,用得出的结果作为数组的下标,则节点p,如果节点p==null,则把元素put到这个位置,这时,表示该hash是第一次出现,即一个新的数组元素。
2:p!=null(该hash值在此HashMap中已经出现过)
1:用p.hash与新元素的hash相比较(p是此hash对应数组元素所对应链表的第一个节点),如果相同则在比较key是否相同,相同则覆盖原来的value,并把该节点更闹心到链表的最后。
2:如果当前计算得出的节点是树节点,则调用putTreeVal()方法;
3:若不是树节点(此时的情况是没有找到相同位置的节点,也不是树节点)此时表示p是一个链表节点
对p为首元素的这个链表进行遍历,如果有key已经存在(hash已经是相同的),则覆盖,并放到链表最后,否则直到最后一个节点的next==null 则新建一个Node把要put的元素放入最后一个新增的节点,然后判断如果当前链表的元素数量,达到了static final int TREEIFY_THRESHOLD = 8 则重新构造当前Hash节点为红黑树结构。

另外put()方法是有返回值的,就是该key原来的value,如果是新的key,则为null。

get()方法源码很容易看,这里就不做详细赘述了。

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值