【Java基础】HashMap

本文详细介绍了Java 1.8中HashMap的基本属性、内部结构、构造函数、重要方法(put、get、remove)以及并发安全性。HashMap使用Node数组作为基础结构,通过计算hash值和索引来分散元素,避免碰撞。在put操作中,当达到特定条件时,HashMap会将链表转化为红黑树以优化性能。在并发环境下,HashMap可能存在数据安全问题,推荐在多线程场景下使用ConcurrentHashMap。
摘要由CSDN通过智能技术生成

本文jdk版本为1.8。

基本属性

/**
 * The default initial capacity - MUST be a power of two.
 */
 //默认初始化容量16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

/**
 * The maximum capacity, used if a higher value is implicitly specified
 * by either of the constructors with arguments.
 * MUST be a power of two <= 1<<30.
 */
 //最大容量2^30
static final int MAXIMUM_CAPACITY = 1 << 30;

/**
 * The load factor used when none specified in constructor.
 */
 //默认负载因子0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;

/**
 * The bin count threshold for using a tree rather than list for a
 * bin.  Bins are converted to trees when adding an element to a
 * bin with at least this many nodes. The value must be greater
 * than 2 and should be at least 8 to mesh with assumptions in
 * tree removal about conversion back to plain bins upon
 * shrinkage.
 */
 //桶上链表节点大于8个时,要进行链表转红黑树
static final int TREEIFY_THRESHOLD = 8;

/**
 * The bin count threshold for untreeifying a (split) bin during a
 * resize operation. Should be less than TREEIFY_THRESHOLD, and at
 * most 6 to mesh with shrinkage detection under removal.
 */
 //跟上个参数相反,小于6个,要进行红黑树转链表
static final int UNTREEIFY_THRESHOLD = 6;

/**
 * The smallest table capacity for which bins may be treeified.
 * (Otherwise the table is resized if too many nodes in a bin.)
 * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
 * between resizing and treeification thresholds.
 */
 //上述链表转红黑树有个前提,就是table的容量最少要64
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;
    }
}

/**
 * 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.)
 */
 //基础结构——数组
transient Node<K,V>[] table;

/**
 * Holds cached entrySet(). Note that AbstractMap fields are used
 * for keySet() and values().
 */
transient Set<Map.Entry<K,V>> entrySet;

/**
 * The number of key-value mappings contained in this 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.)
int threshold;

/**
 * The load factor for the hash table.
 *
 * @serial
 */
final float loadFactor;

基础结构是内部静态类Node<K, V>组成的table数组,Node<K,V>本质上就是个可组成单链表的节点

构造函数

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);
}

public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

几个构造函数都不难理解,都是为了确定table的初始化大小和扩容门限。第一个构造函数稍微说明下,你可以传入指定的容量和负载因子,然后对这个初始化容量进行一个tableSizeFor操作,来看下这个操作是干嘛的。

/**
 * Returns a power of two size for the given target capacity.
 */
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;
}

返回一个大于等于cap且最接近cap的2的整数幂的数,比如你传了个7进来,那我要找比7大的最接近7的2的整数次幂,也就是8。为什么一定要是2的整数次幂,这个后面再说。先看它是怎么实现的,先不管第一行,cap的最高位肯定是1,这里演示的cap足够大。

经过一系列的右移和或操作之后,cap最高位后面的数字全都变成了1,然后再加1,就变成了2的整数次幂。但是有个例外就是cap本身就是2的整数次幂如8,如果按照前面一通操作之后变成了9,违背了最初的意愿,所以第一行会有个减1的操作。这样求最接近7的2整数次幂结果还是8。

重要方法

put

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

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

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    //第一次put时,才进行table的初始化
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)//计算插入table的索引位置
        tab[i] = newNode(hash, key, value, null);
    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);//给LinkedHashMap使用的回调
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)
        //扩容
        resize();
    afterNodeInsertion(evict);//给LinkedHashMap使用的回调
    return null;
}
  • 首先计算key的hash值,key是可以为null
  • new一个HashMap的时候并没有初始化table,而是在第一次put的时候才进行初始化
  • 计算插入索引,拿(table的长度-1) & hash。为什么这么做呢?HashMap的最根本结构是table数组,如何让插入的数据均匀的落在table数组中以减少hash碰撞,直接决定了性能高低。之前提到数组的长度必须是2的整数次幂,这样length -1就从1xxxx--->01111,后面所有位都变成了1,再&上hash值,实现了所有元素均匀地落在数组中的目的(也就是对length取余)。为了防止length不够长,在计算hash的时候,将高16位右移之后再异或上hash值,不浪费hash的高16位。
  • 如果待插入点已经存在Node了,那么需要分情况讨论
  1. 如果当前节点与插入节点相同,更新value
  2. 如果插入节点为红黑树节点,插入红黑树
  3. 否则在已存在节点的链表后面找到相同的点或者在链表的尾部插入新值。如果链表的长度超过转化树的门限,将链表转换为红黑树
  • 如果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倍,扩容门限也是之前的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
        //初始化table
        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"})
    //生成新的table数组
    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;
}

扩容时遍历之前table中的每个节点

  1. 如果节点后没有接任何的Node或者TreeNode,利用新table的长度和节点hash值重新计算要插入的索引
  2. 如果是红黑树节点,调用split方法
  3. 如果节点后还有Node节点,则需要把他们重新分配到新table中。这里直接用hash和oldCap计算新索引,为什么呢?假设oldCap为16(10000),这个节点及后续节点的hash的低4位为0010,现在新table扩充到了32(100000),原节点hash的第5位在计算新索引的时候就派上了用场。会有两种情况,即第5位为0或者1.如果为0,那么计算出的索引(00010)和oldCap的索引是一样的,如果为1,那么就相当于原来的索引加上了16,也就是10010。这样原来同一个链表上的节点就被拆到原索引和原索引+oldCap两个位置了。

get

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

final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    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;
        if ((e = first.next) != null) {
            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;
}
  • 先根据table的长度和hash计算索引,跟put时计算一样(算索引的方式肯定一样,不然put进去不就get不到了吗)
  • 根据计算的索引,如果table上该位置的Node的hash和key与要找的一致,则返回该节点
  • 如果不是,则顺着往后找,根据节点是TreeNode还是Node找法不一,原理都是类似的

remove

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

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 {
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key ||
                         (key != null && key.equals(k)))) {
                        node = e;
                        break;
                    }
                    p = e;
                } while ((e = e.next) != null);
            }
        }
        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);
            else if (node == p)
                tab[index] = node.next;
            else
                p.next = node.next;
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}
  • 跟put、get类似,算索引
  • 找到要找的节点
  • 如果是table数组上节点,需要将该节点后面的链表或者红黑树节点移到数组中来

并发安全性

jdk1.7因为采用的是数组+链表的形式,扩容的时候,采用头插法转移链表数据,并发的时候可能出现链表成环的情况,在get的时候,就会陷入死循环。

jdk1.8采用了数组+链表+红黑树的结构,而且扩容的时候,按照正序转移链表数据,并发的时候不会出现链表成环的情况。但是并发的时候还是会有别的问题,比如数据丢失(多线程同时操作)但是不管1.7还是1.8,HashMap设计的初衷就不是为了并发使用的,所以并发出问题在所难免。

HashTable虽然也是线程安全的,但是用了大量的synchronized来同步,性能不高,并发情况下还是用CurrentHashMap吧

 

参考:https://blog.csdn.net/v123411739/article/details/78996181

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值