JDK源码HashMap

总结:

1.为什么数组容量要是2的次幂

首先当b位2的n次方时,a%b = a & (b-1),所以这样扩容以后,重新计算下标的a%b取模运算就会变成位与操作,有助于提升效率

 if ((p = tab[i = (n - 1) & hash]) == null)  // 在数组第i个位置没有元素
            tab[i] = newNode(hash, key, value, null); //那么插入一个元素到链表头

2.为什么要与h右移16位的值异或,这是为了保留高位的特性,减少冲突,那么为啥不用与和或呢,因为与会将数值向0偏移( 0 & x = 0),或会将数值向1偏移(1 | x = 1),不利于保持高位特性

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

3.为什么要重写equals方法和hashCode方法

hashMap里面会根据equals来判断是否是同一个键,并根据hashCode取模(n-1 & hash)来找到在数组Node<K, V>[]的下标

注意:transient用来阻止该字段序列化

transient Set<Map.Entry<K,V>> entrySet;

对于Entry<K,V>, 它是Map.class里面声明的接口,而HashMap.Class的Node<K,V>实现了该接口:

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> 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;
        }

基于jdk1.8,先看put

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

再看调用的putVal:

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) //tab存的就是链表头数组
// 对table进行扩容(table之前已经插入过对象)或者初始化(初始化数组大小为16,装填因子为0.75,可以点进resize去看)
            n = (tab = resize()).length; 
        if ((p = tab[i = (n - 1) & hash]) == null)  // 在数组第i个位置没有元素
            tab[i] = newNode(hash, key, value, null); //那么插入一个元素到链表头
        else {
            Node<K,V> e; K k;
   // 要插入的元素和当前链表头元素相等(可以是完全相等,或者是元素对象equals方法返回true)
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode) //如果tab[i]是一颗红黑树
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else { //如果tab[i]是一个链表
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null); //元素插入到链表尾部
  // 如果bitCount大于TREEIFY_THRESHOLD(==8) 那么把链表转换成红黑树
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st 
                            treeifyBin(tab, hash); 
                        break;
                    }
// 要插入的元素和当前遍历到的元素相等(可以是完全相等,或者是元素对象equals方法返回true)
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e; //继续下一次循环,这里用到的应该是双指针(p和e)遍历
                }
            }
            
   //这个if就是,当前要插入的元素key,之前在HashMap已经有值
   //那么插入完成后,方法返回之前的老值
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
   //LinkedHashMap要实现的方法,用来把插入的元素放到最后面
                afterNodeAccess(e); 
                return oldValue; //
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

其实就算链表长度超过了8个,也不见得就会转成红黑树,有可能对table进行resize,具体见下:

final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) //MIN_TREEIFY_CAPACITY = 64
            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);
        }
    }

其中resize()的部分代码如下:

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) { // MAXIMUM_CAPACITY = 1 << 30
                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);
        

接下来看get:

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

看它调用的getNode:

final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
//先看要查找的元素和链表头元素是否相等(完全相等或者equals返回true,同上文putVal)
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
//如果first是红黑树,调用getTreeNode
                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;
    }

继续看getTreeNode

final TreeNode<K,V> getTreeNode(int h, Object k) {
            return ((parent != null) ? root() : this).find(h, k, null);
        }

其中的root()方法:

/**
         * Returns root of tree containing this node. 返回当前节点的tree根节点
         */
        final TreeNode<K,V> root() {
            for (TreeNode<K,V> r = this, p;;) {
                if ((p = r.parent) == null)
                    return r;
                r = p;
            }
        }

再看find方法:

final HashMap.TreeNode<K, V> find(int h, Object k, Class<?> kc) {
            HashMap.TreeNode p = this;

            do {
                HashMap.TreeNode<K, V> pl = p.left;
                HashMap.TreeNode<K, V> pr = p.right;
                int ph;
//h就是hash值,根据hash值来判断应该往左节点或者右节点走,也能够看出这个树是一棵有序树
                if ((ph = p.hash) > h) {
                    p = pl;
                } else if (ph < h) {
                    p = pr;
                } else {
                    Object pk;
                    //找到指定元素就返回
                    if ((pk = p.key) == k || k != null && k.equals(pk)) {
                        return p;
                    }

                    if (pl == null) {
                        p = pr;
                    } else if (pr == null) {
                        p = pl;
                    } else {
//走到这里的情况就是,要查找的元素hash值和目前遍历到的节点hash值是一样的
                        int dir;
                        if ((kc != null || (kc = HashMap.comparableClassFor(k)) != null) && (dir = HashMap.compareComparables(kc, k, pk)) != 0) {
//dir为0就走到右节点,这也就意味着,key相同时,后面插入的元素都认为比之前的'大',总之后插入就在右边(符合红黑树定义)
                            p = dir < 0 ? pl : pr;
                        } else {
                            HashMap.TreeNode q;
                            if ((q = pr.find(h, k, kc)) != null) {
                                return q;
                            }

                            p = pl;
                        }
                    }
                }
            } while(p != null);

            return null;
    }

这里面又有comparableClassFor:

/**
* 如果对象x的类是C,如果C实现了Comparable<C>接口,那么返回C,否则返回null
*/
static Class<?> comparableClassFor(Object x) {
    if (x instanceof Comparable) {
        Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
        if ((c = x.getClass()) == String.class) // 如果x是个字符串对象
            return c; // 返回String.class
        /*
         * 为什么如果x是个字符串就直接返回c了呢 ? 因为String  实现了 Comparable 接口,可参考如下String类的定义
         * public final class String implements java.io.Serializable, Comparable<String>, CharSequence
         */ 
 
        // 如果 c 不是字符串类,获取c直接实现的接口(如果是泛型接口则附带泛型信息)    
        if ((ts = c.getGenericInterfaces()) != null) {
            for (int i = 0; i < ts.length; ++i) { // 遍历接口数组
                // 如果当前接口t是个泛型接口 
                // 如果该泛型接口t的原始类型p 是 Comparable 接口
                // 如果该Comparable接口p只定义了一个泛型参数
                // 如果这一个泛型参数的类型就是c,那么返回c
                if (((t = ts[i]) instanceof ParameterizedType) &&
                    ((p = (ParameterizedType)t).getRawType() ==
                        Comparable.class) &&
                    (as = p.getActualTypeArguments()) != null &&
                    as.length == 1 && as[0] == c) // type arg is c
                    return c;
            }
            // 上面for循环的目的就是为了看看x的class是否 implements  Comparable<x的class>
        }
    }
    return null; // 如果c并没有实现 Comparable<c> 那么返回空
}

参考 https://blog.csdn.net/weixin_42340670/article/details/80673127

如果继承了Comparable接口,那么就会走到HashMap.compareComparable()方法:

static int compareComparables(Class<?> kc, Object k, Object x) {
        return (x == null || x.getClass() != kc ? 0 :
                ((Comparable)k).compareTo(x));
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值