JAVA集合HashMap源码总结

/**
     * 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;
        //开始判断hash表是否为空,若果为null,通过resize扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //hash是通过key计算得出的,然后得到下标i,然后判断这个位置是否是null
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);//如果为null,那么建立链表头结点
        else {
        //如果这个位置不是空那么要进行循环判断是否有这个key
            Node<K,V> e; K k;
            //查看当前节点和key计算出的hash是否相同,(1.hashcode 2.equeals比较),如果一样就更新 (hashcode相同但equals可能不同)
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //hash表头结点和key不一样,判断节点是否是红黑树,如果是红黑树 按红黑树处理
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
            //如果不是红黑树 那么按照hash表原理进行处理
            //遍历这个下标的链表
                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 如果长度大于等于TREEIFY_THRESHOLD-1,转换为红黑树结构,针对红黑树的插入来插入
                            treeifyBin(tab, hash);
                        break;
                    }
                    //如果找到相同的key 那么覆盖即可
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //如果e不是null(找到key相同的break了),那么添加新值返回旧值
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        //没找到相同的 ,那么增加了一个
        //所以modCount 增加一个
        ++modCount;
        //如果threshold小于增加后的size 那么进行扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

下面是get

final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        //先看表是否是null,表长是否大于0,第一个是否为null
        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;
                //看第一个节点的下一个是否为null
            if ((e = first.next) != null) {
                //是否是treeNode 
                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;
    }

resize():扩容原理是使用新的(二倍旧长度)的数组代替,把旧数组的内容放入新数组中,这时,需要重新计算hash和计算hash表的位置,但JDK1.8对hashmap引入了红黑树,对扩容方法进行改进。

/**
    吓死我了这么长 QvQ
    初始化或者2倍table长度,如果null,分配的空间,初始容量和属性threshold相同的大小
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * 然而,我们使用了2倍进行扩大,元素必须要么在相同下标要么移动
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * 在新table中个2倍的offset(开端)
     * with a power of two offset in the new table.
     *
     * @return the table
     */
    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;
            }
            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;
            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;
                    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;
    }

扩容查看二进制新增位是0还是1如果是0,rehash索引不变,否则变为原来的索引+旧hash表的长度。并不用像以前那样,重新计算hash值得时间,resize均匀的把之前的冲突节点分散。

HashMap是非线程安全的,在多线程中可以使用concurrentHashMap
HashMap实现了实现了Serializable接口,因此它支持序列化。
HashMap还实现了Cloneable接口,故能被克隆。
HashMap中数组的每个元素都是单链表的头结点,链表用来解决Hash冲突问题。

HashMap什么时候需要扩容?
size > initialCapacity(默认16) * loadFactor(默认0.75)时,HashMap内部resize方法会被调用,重新扩充hash桶数量,一般不存在键值放满,特殊情况(JVM内存用完,Capacity到达最大值2的30次方)
loadFactor过大,空间利用率会提高,桶中链表长度增长。
initialCapacity过大,可能会使迭代器效率降低。

HashMap中的key可以为空,并且是在table[0]这一个单链表中。
HashMap使用链地址法解决冲突,并使用头插来对元素进行插入。

HashMap和HashTable的改进之处?
HashMap计算位置使用 hash & (length - 1)(效率高)
HashTable使用 hash值对length取模

1、能否使HashMap实现线程安全
可以。
1.使用HashTable,当一个线程访问HashTable的同步方法时,如果其他线程也要访问同步方法,将会被阻塞。
2.使用Collections.synchronizedMap(hashmap);来实现hashmap同步
3.使用ConcurrentHashMap

2、关于synchroniezedMap()

public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
        return new SynchronizedMap<>(m); //返回一个SynchronizedMap类对象
    }

    /**
     * @serial include 可序列化
     */
    private static class SynchronizedMap<K,V>
        implements Map<K,V>, Serializable {
        private static final long serialVersionUID = 1978198479659022715L;

        private final Map<K,V> m;     // Backing Map
        final Object      mutex;        // Object on which to synchronize

        SynchronizedMap(Map<K,V> m) {
        //requireNonNull(T)方法时,当传入的参数不为null时,返回参数本身,反之,抛出一个NullPointerException异常。
            this.m = Objects.requireNonNull(m);
            //锁是synchronizedMap这个对象。
            mutex = this;
        }
        //可以传入一把指定的锁 否则使用this
        SynchronizedMap(Map<K,V> m, Object mutex) {
            this.m = m;
            this.mutex = mutex;
        }
        //每次进行都要用mutex 来进行上锁
        public int size() {
            synchronized (mutex) {return m.size();}
        }
        public boolean isEmpty() {
            synchronized (mutex) {return m.isEmpty();}
        }
        public boolean containsKey(Object key) {
            synchronized (mutex) {return m.containsKey(key);}
        }
        public boolean containsValue(Object value) {
            synchronized (mutex) {return m.containsValue(value);}
        }
        public V get(Object key) {
            synchronized (mutex) {return m.get(key);}
        }

        public V put(K key, V value) {
            synchronized (mutex) {return m.put(key, value);}
        }
        public V remove(Object key) {
            synchronized (mutex) {return m.remove(key);}
        }
        public void putAll(Map<? extends K, ? extends V> map) {
            synchronized (mutex) {m.putAll(map);}
        }
        public void clear() {
            synchronized (mutex) {m.clear();}
        }

        private transient Set<K> keySet;
        private transient Set<Map.Entry<K,V>> entrySet;
        private transient Collection<V> values;

        public Set<K> keySet() {
            synchronized (mutex) {
                if (keySet==null)
                    keySet = new SynchronizedSet<>(m.keySet(), mutex);
                return keySet;
            }
        }

        public Set<Map.Entry<K,V>> entrySet() {
            synchronized (mutex) {
                if (entrySet==null)
                    entrySet = new SynchronizedSet<>(m.entrySet(), mutex);
                return entrySet;
            }
        }

        public Collection<V> values() {
            synchronized (mutex) {
                if (values==null)
                    values = new SynchronizedCollection<>(m.values(), mutex);
                return values;
            }
        }

        public boolean equals(Object o) {
            if (this == o)
                return true;
            synchronized (mutex) {return m.equals(o);}
        }
        public int hashCode() {
            synchronized (mutex) {return m.hashCode();}
        }
        public String toString() {
            synchronized (mutex) {return m.toString();}
        }

        // Override default methods in Map
        @Override
        public V getOrDefault(Object k, V defaultValue) {
            synchronized (mutex) {return m.getOrDefault(k, defaultValue);}
        }
        @Override
        public void forEach(BiConsumer<? super K, ? super V> action) {
            synchronized (mutex) {m.forEach(action);}
        }
        @Override
        public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
            synchronized (mutex) {m.replaceAll(function);}
        }
        @Override
        public V putIfAbsent(K key, V value) {
            synchronized (mutex) {return m.putIfAbsent(key, value);}
        }
        @Override
        public boolean remove(Object key, Object value) {
            synchronized (mutex) {return m.remove(key, value);}
        }
        //省略方法

在SynchronizedMap类中使用了synchronized来保证对Map的操作是线程安全的,效率也不高。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值