栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

HashMap源码分析

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

HashMap源码分析

HashMap是平时编码使用频繁的类,也是面试会经常问到的东西,源码有非常多的精妙的设计,通过阅读源码分析HashMap是非常有必要的,由于篇幅所限,在此只分析部分重要方法。

HashMap和HashTable非常的相似,除了它是不同步的(非线程安全)并且可以为空值(key ,value)。不过可以通过Collections.synchronizedMap方法使其同步。
下面先用图(来源)来描绘一下HashMap。

HashMap由数组+链表+红黑树构成。HashMap继承AbstractMap并实现Map,Cloneable,Serializable接口。要注意HashMap的实例有两个影响其性能的参数:初始容量和负载因子。

  1. 负载因子
 
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
  1. 初始容量
 
    static final int DEFAULT_INITIAL_CAPACITY=16;

为什么要是2的幂?
:HashMap为提高get put效率,减少碰撞。取模算法hash%length ,hashmap将其优化成位运算hash&(length-1),但hash%length等于hash&(length-1)的前提是length是2的n次幂。

红黑树与链表转化的关键成员变量

    static final int TREEIFY_THRESHOLD = 8;

    
    static final int UNTREEIFY_THRESHOLD = 6;

    
    static final int MIN_TREEIFY_CAPACITY = 64;

当这个链表长度大于阈值8并且数组长度大于64则进行将链表变为红黑树。
将链表转换成红黑树前会判断,如果阈值大于8,但是数组长度小64,此时并不会将链表变为红黑树。而是选择进行数组扩容。
以上都是为了提升性能和效率,红黑树为维持平衡本身有一定开销

数组表:

    transient Node[] table;

fail-fast 机制变量

    transient int modCount;

其余的成员变量:

 	
    static final int MAXIMUM_CAPACITY = 1 << 30;
	
    transient int size;
	
	 
    int threshold;
    
    
    final float loadFactor;

基本的Node节点

    static class Node implements Map.Entry{

        final int hash;
        final K key;
        V value;
        Node next;

      // ...get set

        @Override
        public V setValue(V newValue) {
            V oldValue = value;
            value=newValue;
            return oldValue;
        }
        @Override
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        @Override
        public boolean equals(Object obj) {
            //如果是同一个对象
            if(obj==this){
                return true;
            }
            //否则先判断类型,再比较键和值
            if (obj instanceof Map.Entry) {
                Map.Entry e = (Map.Entry)obj;
                if (Objects.equals(key, e.getKey()) &&
                        Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }

       
    }

初始化
这里可以注意到,初始化时并没有创建数组,而是在第一次写入时创建。

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;
       
        this.threshold = tableSizeFor(initialCapacity);
    }
    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;
    }

put操作

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

    
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node[] tab; Node 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 e; K k;
            //如果要要放的位置有元素了
            //如果要放的元素的key等于原有的元素的key
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
                //如果是红黑树,按照红黑树的方式放
            else if (p instanceof TreeNode)
                e = ((TreeNode)p).putTreeval(this, tab, hash, key, value);
            else {
            //还是list,按照list的方式放,循环查找
                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;
                }
            }
            // 新key和旧key相同,直接覆盖
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        //帮助fail-fast的参数
        ++modCount;
        //判断大小,扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

读取

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

    
    final Node getNode(int hash, Object key) {
        Node[] tab; Node first, e; int n; K k;
        //判空
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            //检查第一个的key
            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)first).getTreeNode(hash, key);
            //如果是list
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

扩容

 
    final Node[] resize() {
        Node[] oldTab = table;
        //旧的容量
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        //旧的阀值
        int oldThr = threshold;
        int newCap, newThr = 0;
        //判断初始
        if (oldCap > 0) {
        //判断初始大小,如果大于等于最大默认容量则把阀值变为Integer的最大值,暂时不扩容
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //否则,扩容变为原来容量的两倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        //旧容量<=0,阀值大于0
        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);
        }
        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[] newTab = (Node[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
        //for循环,对所有元素Hash
            for (int j = 0; j < oldCap; ++j) {
                Node e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                       //如果是树
                    else if (e instanceof TreeNode)
                        ((TreeNode)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        Node loHead = null, loTail = null;
                        Node hiHead = null, hiTail = null;
                        Node 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;
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/643761.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号