冲击Hash---HashMap源码1.8

HashMap中Node

public final int hashCode() {   
 	 return Objects.hashCode(key) ^ Objects.hashCode(value);
} 
key的hashcode和key右移16位数字做亦或操作
static final int hash(Object key) {
     int h;
     return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//返回一个比给定整数大且最接近的2的幂次方整数
//n |= n >>> 1;也就是n变成n与n右移一位之后或运算的值
static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

术语总结:

^:亦或同为0,异为1

>>>:>>>表示无符号右移,忽略符号位,空位都以0补齐

| =:按位或a=a|b

链表散列:数组加链表

HashMap源码分析

先看基本结构图吧,散列表+红黑树的实现。

img

一、构造函数

构造函数分为两类

  • 容器大小,加载因子
这三个是参数不同,但原理相似
//默认加载因子0.75
HashMap(){
     this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
//加载因子0.75,指定初始化容量
HashMap(int initialCapacity) {
     this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
HashMap(int initialCapacity, float loadFactor){
		//。。。
		核心方法,指定初始化容量大小;上面分析了这个方法,大概就是给定整数大且最接近的2的幂次方整数;
		tableSizeFor(initialCapacity)
		//。。。
}
  • 指定Map内容

    //map传递给map,马上就到核心了。节奏有点快
    public HashMap(Map<? extends K, ? extends V> m) {
         this.loadFactor = DEFAULT_LOAD_FACTOR;
         putMapEntries(m, false);
    }
    

深入阶段

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            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);
            }
            //通过构造函数是不会走这一步的,因为table一定为空
            else if (s > threshold)
                resize();
            //将传参加入到table
            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);
            }
        }
    }

承接上面重载的构造函数,但并不代表它就是进入核心的关键路径,反倒是putMapEntries()中的实现tableSizeFor(),putVal(),resize()才是艰难又精彩的部分;

tableSizeFor()

上文说过这个点,也不用细究,反正也会忘记;记住这是为了指定数字最接近的2次幂结果

死记硬背一下源码就行了

static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

putVal()

显而易见是增加元素给容器的

构造函数中的调用方式

1.转换为EntrySet,大致了解它是一个Set<Map>类型就行;
2.计算hash值;实现在上方,就是自身与自身右移16位进行亦或操作
3.final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict)
    
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);
}

putVal();

先判断大体函数如何执行的

img

辅助putVal()的函数

//新建节点
Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
        return new Node<>(hash, key, value, next);
}

1.通过 (n - 1) & hash 判断当前元素存放的位置

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为空,则做扩容操作
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
    	//计算hash值,判断数组中当前节点是否有元素,没有则newNode
    	//(数组当前长度-1)&hash值得到数组位置;这儿就是做了取余运算hash%n
    	//p也就是链表的引用  例子:(16-1)&hash = hash%64
        if ((p = tab[i = (n - 1) & hash]) == null)
           	//辅助函数,新建节点
            tab[i] = newNode(hash, key, value, null);
        else {
            //table[i]有元素,注意这儿命名,e代表existing
            Node<K,V> e; K k;
            //hash相同,且key也相同,然后覆盖
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //当前节点为TreeNode类型,此处为红黑树专栏,等会重点分析
            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);
                        //当链表长度大于阈值(默认为8)时,将链表转化为红黑树,以减少搜索时间
                        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;
            }
        }
    	//为新增操作时,返回空,覆盖返回oldValue
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

resize()扩容

调用条件:基本条件是容量大于阈值;

注意:进行扩容,会伴随着一次重新hash分配,并且会遍历hash表中所有的元素,是非常耗时的。在编写程序中,要尽量避免resize。

  • 所以在此有必要调查一下哪些地方会用到resize()

    • HashMap(Map<? extends K, ? extends V> m) {
       putMapEntries(m, false);
       }
       public void putAll(Map<? extends K, ? extends V> m) {
       putMapEntries(m, true);
       }
      public Object clone() {
      result.putMapEntries(this, false);
      }
      putMapEntries函数中调用方式;//threshold现在的扩容临界值
      当table不为空且(m.size() > threshold) ==> resize();          
      
  • putVal()

  • 当table为空,则进行扩容操作
    if ((tab = table) == null || (n = tab.length) == 0)
          n = (tab = resize()).length;
    当当前容器数量大于扩容临界值,则进行扩容
    if (++size > threshold)
          resize();
    
  - 然后就是红黑树中涉及到的
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) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //oldCap*2>初始容量 一句话 扩容=容量*2;阈值*2
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                //阈值*2
                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;
            //阈值(12)=负载因子(0.75)*初始容量(16)
            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<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
      //当前不为空,扩容链表位置就需要重新定位
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    //清空原有元素
                    oldTab[j] = null;
                    //无链表,新位置等于hash%newCap
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> 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;
    }

remove()删除

public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ?
        null : e.value;
}

//value =null, matchValue=false,movable=true
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;
    //赋值,定位对应元素位置
    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 {
                //循环查找key相匹配的node
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key ||
                         (key != null && key.equals(k)))) {
                        node = e;
                        break;
                    }
                    p = e;
                } while ((e = e.next) != null);
            }
        }
        //定位到node,
        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);
            //为最后一个节点(也包含单一节点),所以直接把tab[index]置为空
            else if (node == p)
                tab[index] = node.next;
            //链表中间节点
            else
                //前一个元素的下一个置为当前元素的下一个
                p.next = node.next;
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值