HashMap构造函数

HashMap()

/**
 * Constructs an empty <tt>HashMap</tt> with the default initial capacity
 * (16) and the default load factor (0.75).
 * 这是一个默认的构造方法,初始化的容量大小是16,装填因子是0.75
 * a 装填因子
 * n 关键字个数
 * m 总容量
 * a = n/m
 * 这里的容量大小为16,装填因子是0.75,就表示当内容达到12个的时候就会可能出现Hash冲突
 * 必须在 "冲突的机会"与"空间利用率"之间寻找一种平衡与折衷.这种平衡与折衷本质上是数据 * 结构中有名的"时-空"矛盾的平衡与折衷.也就是说在空间与时间上
 */
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

HashMap(int initialCapacity)

 /**
 * Constructs an empty <tt>HashMap</tt> with the specified initial
 * capacity and the default load factor (0.75).
 *
 * @param  initialCapacity the initial capacity.
 * @throws IllegalArgumentException if the initial capacity is negative.
 */
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

HashMap(int initialCapacity, float loadFactor)

/**
 * Constructs an empty <tt>HashMap</tt> with the specified initial
 * capacity and load factor.
 * 指定容量指定装填因子
 * @param  initialCapacity the initial capacity
 * @param  loadFactor      the load factor
 * @throws IllegalArgumentException if the initial capacity is negative
 *         or the load factor is nonpositive
 */
public HashMap(int initialCapacity, float loadFactor) {
    //如果初始化容量小于零
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " +
                                           initialCapacity);
    //如果初始化容量大于 1 << 30 左移表示乘以多少个 2 ,也就是表示 2的30次方;
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;
    //如果装填因子小于等于0
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " +
                                           loadFactor);
    this.loadFactor = loadFactor;
    this.threshold = tableSizeFor(initialCapacity);
}

示例

HashMap<Integer,String> hashMap = new HashMap<Integer, String>(-1,0.5f);

在这里插入图片描述

初始化容量操作

HashMap<Integer,String> hashMap = new HashMap<>(1<<32,0.5f);

this.threshold = tableSizeFor(initialCapacity);

/**
 * The next size value at which to resize (capacity * load factor).
 *
 * @serial
 */
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
int threshold;

表示获取最接近初始化值的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;
}

首先,int n = cap -1是为了防止cap已经是2的幂时,执行完后面的几条无符号右移操作之后,返回的capacity是这个cap的2倍,因为cap已经是2的幂了,就已经满足条件了。 如果不懂可以往下看完几个无符号移位后再回来看。(建议自己在纸上画一下)

如果n这时为0了(经过了cap-1之后),则经过后面的几次无符号右移依然是0,最后返回的capacity是1(最后有个n+1的操作)。这里只讨论n不等于0的情况。
以16位为例,假设开始时 n 为 0000 1xxx xxxx xxxx (x代表不关心0还是1)

  • 第一次右移 n |= n >>> 1;

由于n不等于0,则n的二进制表示中总会有一bit为1,这时考虑最高位的1。通过无符号右移1位,则将最高位的1右移了1位,再做或操作,使得n的二进制表示中与最高位的1紧邻的右边一位也为1,如0000 11xx xxxx xxxx 。

  • 第二次右移 n |= n >>> 2;

注意,这个n已经经过了n |= n >>> 1; 操作。此时n为0000 11xx xxxx xxxx ,则n无符号右移两位,会将最高位两个连续的1右移两位,然后再与原来的n做或操作,这样n的二进制表示的高位中会有4个连续的1。如0000 1111 xxxx xxxx 。

  • 第三次右移 n |= n >>> 4;

这次把已经有的高位中的连续的4个1,右移4位,再做或操作,这样n的二进制表示的高位中会有8个连续的1。如0000 1111 1111 xxxx 。

测试结果

public static void main(String[] args) {
        int sizeFor = tableSizeFor(432);
        System.out.println(sizeFor);
        //>>>  :  无符号右移,忽略符号位,空位都以0补齐
        //00000000_00000000_00000000_00000111   7
        //00000000_00000000_00000000_00000011   3
        int a = 7 >>> 1;
        System.out.println(a);
        //00000000_00000000_00000000_00000111  7
        //00000000_00000000_00000000_00000011  3
        int b = 7;
        //按位或的结果
        //00000000_00000000_00000000_00000111
        b |= 3;
        System.out.println(b);
        b |= b>>>1;
        System.out.println(b);
}
// 此函数返回的结果表示获取最接近它的2的次方
static  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 >= 1<<30) ? 1<<30 : n + 1;
}

HashMap(Map<? extends K, ? extends V> m)

 /**
 * Constructs a new <tt>HashMap</tt> with the same mappings as the
 * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
 * default load factor (0.75) and an initial capacity sufficient to
 * hold the mappings in the specified <tt>Map</tt>.
 *
 * @param   m the map whose mappings are to be placed in this map
 * @throws  NullPointerException if the specified map is null
 */
public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

调用了putMapEntries(m, false);方法

/**
 * Implements Map.putAll and Map constructor
 *
 * @param m the map
 * @param evict false when initially constructing this map, else
 * true (relayed to method afterNodeInsertion).
 */
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
    // 获取现有Map的大小
    int s = m.size();
    // 当m 中有元素的时候,将Map中的元素放入到现在初始化的这个Map实例中
    if (s > 0) {
        //  判断table是否已经被初始化了,如果没有初始化先需要进行初始化一些变量
        //  例如装填因子初始化容量等参数
        if (table == null) { // pre-size
            //根据待插入的map的Size计算需要创建的Map的容量
            float ft = ((float)s / loadFactor) + 1.0F;
            //计算对应容量
            int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                     (int)ft : MAXIMUM_CAPACITY);
            // 要把创建的的map的容量存在 threshold 中
            if (t > threshold)
                threshold = tableSizeFor(t);
        }
        //如果table初始化过了,因为还有其他函数的调用,所以有些Hashmap已经被初始化过了
        //判断需要插入的值是否大于现有的threshold,如果需要,则进行扩容操作resize();
        else if (s > threshold)
            resize();
        //然后就开始遍历需要插入的map ,将每一个KV都插入的本实例HashMap中
        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,在HashMap出入值调用put方法的时候实际上也是调用这个方法。下一边分析一边来看看具体的参数都是什么意思

首先先来介绍一下HashMap中的几个私有属性

 /**
 * The table, initialized on first use, and resized as
 * necessary. When allocated, length is always a power of two.
 * (We also tolerate length zero in some operations to allow
 * bootstrapping mechanics that are currently not needed.)
 */
 // 用来存储实际的key,value的数组,只不过在HashMap中将其封装成了一个Node,下面会介绍
transient Node<K,V>[] table;
/**
 * Holds cached entrySet(). Note that AbstractMap fields are used
 * for keySet() and values().
 */
 //作为一个Key的缓存存在
transient Set<Map.Entry<K,V>> entrySet;
/**
 * The number of key-value mappings contained in this map.
 */
//Map中已有数据的大小
transient int size;
/**
 * The number of times this HashMap has been structurally modified
 * Structural modifications are those that change the number of mappings in
 * the HashMap or otherwise modify its internal structure (e.g.,
 * rehash).  This field is used to make iterators on Collection-views of
 * the HashMap fail-fast.  (See ConcurrentModificationException).
 */
 
transient int modCount;
/**
 * The next size value at which to resize (capacity * load factor).
 *
 * @serial
 */
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
// 因为 tableSizeFor(int) 返回值给了threshold
int threshold;
/**
 * The load factor for the hash table.
 *
 * @serial
 */
final float loadFactor;

在这里插入图片描述

这里首先关注两个点

Entry
Entry 是由Map提供的接口

在这里插入图片描述

Node
在这里插入图片描述

/**
 * Basic hash bin node, used for most entries.  (See below for
 * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
 */
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;
    }
}

会看到在上面调用了putMapEntries 方法的时候调用了一个putVal而在传入参数的时候调用了一个hash()方法

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

这里有个异或运算

(h = key.hashCode()) ^ (h >>> 16);

这里我们知道Hash值是一个int类型的使用2个字节,也就是16位二进制表示

原 来 的 hashCode : 1111 1111 1111 1111 0100 1100 0000 1010
移位后的hashCode: 0000 0000 0000 0000 1111 1111 1111 1111
进行异或运算 结果:1111 1111 1111 1111 1011 0011 1111 0101

这样做的好处是,可以将hashCode高位和地位的值进行混合做异或运算,而且混合之后,地位的信息中加入了高位的信息,这样高位的信息就会被保留下来,掺杂的元素多了,那么生成的hash的随机性会增大。

这里在补充分析一下另外的一个方法扩容方法resize()

/**
 * Initializes or doubles table size.  If null, allocates in
 * accord with initial capacity target held in field threshold.
 * Otherwise, because we are using power-of-two expansion, the
 * elements from each bin must either stay at same index, or move
 * with a power of two offset in the new table.
 *
 * @return the table
 */
final Node<K,V>[] resize() {
    //保存当前table
    Node<K,V>[] oldTab = table;
    //保存当前table容量
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    //保存当前阈值
    int oldThr = threshold;
    //初始化新的Table的容量和阈值
    int newCap, newThr = 0;
    /**
    1、resize()函数在size > threshold 的时候被调用,
    oldCap 大于0 表示原来的table为非空,oldCap为原来表大小,
    oldThread 为原来容量oldCap x load_factor
    */
    if (oldCap > 0) {
        // 如果旧的table容量超过最大容量,更新阈值为最大整型值这样以后就不需要再操作了
        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
    }
    /**
    2、resize() 函数在table为空的时候调用,oldCap等于0且oldThr 大于0,代表用户创建了一个 HashMap ,但是使用的构造函数为HashMap(int initialCapacity, float loadFactor)或者HashMap(int initialCapacity)或 HashMap(Map<? extends K, ? extends V> m),导致 oldTab 为 null,oldCap 为0, oldThr 为用户指定的 HashMap的初始容量。
    */
    
    else if (oldThr > 0) // initial capacity was placed in threshold
        //当table没初始化时,threshold持有初始容量
        newCap = oldThr;
    /**
    3、resize() 函数在table为空被调用,oldCap小于等于0且oldThr等于0,用户调用了HasHMap()构造函数 HashMap,所有值均采用默认值,oldTab(Table)表为空,oldCap为0,oldThr等于0
    */
    else {               // zero initial threshold signifies using defaults
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    //新的阈值 为 0
    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"})
    //初始化table
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
    if (oldTab != null) {
        //把oldTab 中的节点 reHash 到 newTab中去
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                // 如果是一个单节点,直接再newTab中进行定位
                if (e.next == null)
                    newTab[e.hash & (newCap - 1)] = e;
                // 如果节点是一个TreeNode 要进行红黑树的 reHash操作
                else if (e instanceof TreeNode)
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                // 如果是一个链表,进行链表的reHash操作
                else { // preserve order
                    Node<K,V> loHead = null, loTail = null;
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    //(e.hash & oldCap)按位与 是否为零
                    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;
}

链表扩容
在这里插入图片描述

什么时候进行扩容

通过HashMap源码可以看到是在put操作时,即向容器中添加元素时,判断当前容器中元素的个数是否达到阈值(当前数组长度乘以加载因子的值)的时候,就要自动扩容了。

扩容(resize):其实就是重新计算容量;而这个扩容是计算出所需容器的大小之后重新定义一个新的容器,将原来容器中的元素放入其中。


/**
 * 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;
    //判断table是否为空或者长度为0,则进行resize();
    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);
    //当发生碰撞的时候,有两种情况,1、key值一样替换value值
    // 2、key值不一样
    // 2.1
    else {
        Node<K,V> e; K k;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        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);
                    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;
        }
    }
    ++modCount;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nihui123

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值