Hashmap源码解析(jdk1.8)及面试问题

Hashmap源码分析

import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import sun.misc.SharedSecrets;
  • Hash table 是基于Map接口的实现。Hashmap的提供了所有可选的map操作并允许键和值为 null (除了不同步和允许空值,HashMap大致相当于Hashtable) Hashmap的遍历顺序是不确定的。
  • Hashmap的实例有两个影响其性能的参数:初始容量和加载因子,容量是哈希表中桶的数量,初始容量是哈希表创建时的容量,加载因子是哈希表在其容量自动增加之前可以达到多满的一种尺度。
    当哈希表中的实体数量超过加载因子 * 容量时,则要对该哈希表进行 rehash 操作(即重建内部数据结构),哈希表将扩容为大约两倍的桶数。
  • 基本规则是默认加载因子为0.75,这样在时间和空间成本之间形成了一个良好的折中。
  • 在设置初始容量时应该考虑到映射中所需的条目数及其加载因子,以便最大限度地减少 rehash 操作次数。如果初始容量大于最大条目数除以加载因子,则不会发生 rehash 操作。
  • 如果有许多映射要存储在HashMap实例中,那么在创建哈希表时使用足够大的初始容量存储效率将高于根据需要增大表的大小执行自动重新散列。
  • Hashmap是线程不安全的,如果多个线程同时访问一个哈希映射,并且至少有一个线程修改映射结构,必须在外部进行同步操作。(结构修改是添加或删除一个或多个映射的操作,只是改变已经存在的实例的与关键字相关的值不是结构修改。)
  • fast-fail事件:当多个线程对Collection进行操作时,若其中某一个线程通过iterator去遍历集合时,该集合的内容被其他线程所改变;则会抛出ConcurrentModificationException异常。因此,当存在并发修改时,迭代器会快速失败。迭代器的快速失败行为不能得到保证,一般来说,存在非同步的并发修改时,不可能作出任何坚决的保证。快速失败迭代器尽最大努力抛出 ConcurrentModificationException。因此,编写依赖于此异常的程序的做法是错误的,正确做法是:迭代器的快速失败行为应该仅用于检测程序错误。

    public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
    private static final long serialVersionUID = 362498820763181265L;
    //默认初始容量是16,必须是2的幂(为什么?后面介绍)
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    //最大容量,当使用带参构造函数指定初始容量时使用,避免指定的初始容量大于最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;
    //默认加载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    //桶的技术阈值,当添加元素时桶中的数量至少有这些时应该转换为树,而不是继续使用链表
    static final int TREEIFY_THRESHOLD = 8;
    static final int UNTREEIFY_THRESHOLD = 6;
    static final int MIN_TREEIFY_CAPACITY = 64;
    • 哈希桶结点的定义
 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;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }
  • 计算key.hashCode(),高位运算
    h = key.hashCode()为32位,将这32位的高16位于低16位进行异或运算,是高低bit都参与运算。二进制运算比模运算的效率要高。
static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
  • Hashmap的带参构造函数分析:
    如果初始容量小于0或者加载因子小于等于0都会抛出IllegalArgumentException异常
    设置的初始容量大于最大容量时,将初始容量设置为最大容量。
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);
    }

持续更新。。。。。。。。

猜你喜欢

转载自blog.csdn.net/ningchunmei1/article/details/80003107