Java集合-HashMap

  HashMap是Java中实现了Map接口的一种数据结构,它提供了一种存储键值对的方式。HashMap基于哈希表实现,具有快速的查找性能,平均情况下,插入、删除和获取元素的时间复杂度都是O(1)。

以下是HashMap的主要特点和使用方法:

1、键值对存储:HashMap存储的是键值对(key-value pair),每个键都是唯一的,而值可以重复。通过键来获取值,可以快速查找、插入和删除元素。

2、哈希表实现:HashMap内部使用了一个数组来存储元素,每个元素是一个链表或红黑树的头节点。在插入元素时,通过对键进行哈希计算,确定元素在数组中的位置,然后将元素插入到对应位置的链表或树中。

3、键的唯一性:在HashMap中,每个键都必须是唯一的。如果添加了重复的键,则新的值将覆盖旧的值。但是,值可以是重复的。

4、非线程安全:HashMap不是线程安全的,如果多个线程同时访问和修改HashMap,可能会导致数据不一致的问题。如果需要在多线程环境中使用,可以考虑使用ConcurrentHashMap或通过同步手段来保证线程安全。

5、迭代顺序不固定:HashMap的迭代顺序不是固定的,取决于元素的哈希码及其在数组中的位置。因此,不要依赖于迭代顺序。

6、容量和负载因子:HashMap有两个重要的参数:初始容量和负载因子。初始容量是哈希表中桶的数量,默认为16;负载因子是哈希表在容量自动增加之前可以达到多满的一个度量,默认为0.75。当哈希表的大小超过负载因子与当前容量的乘积时,将会重新调整大小。

我们先来看一下HashMap的属性常量

/**
 * The default initial capacity - MUST be a power of two.
 */
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.
 * 最大容量,为什么int的最大值2^31-1呢?和扩容机制有关,保证容量为2的幂
 */
static final int MAXIMUM_CAPACITY = 1 << 30;

/**
 * The load factor used when none specified in constructor.
 * 默认扩容负载因子
 */
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.
 * 树化阈值
 */
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.
 * 链化阈值
 */
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.
 * TREEIFY_THRESHOLD达到8也不一定树化,必须保证总容量达到64
 */
static final int MIN_TREEIFY_CAPACITY = 64;

实例属性

/**
 * 哈希表,懒初始化(在第一次存入元素的时候),自动调整大小,长度为2的倍数
 */
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;

/**
 * 元素个数
 */
transient int size;

/**
 * 迭代时的并发修改次数
 */
transient int modCount;

/**
 * 当前容量与负载因子的乘积,表示下次扩容的元素个数阈值
 */
// (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;

/**
 * 负载因子,默认0.75
 * @serial
 */
final float loadFactor;

构造函数

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

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

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(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

public V put(K key,V value)

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

首先会根据key获取hash值:

HashMap仅允许一个元素的键为null,其hash用0代替
获取key的hashCode值,高16位和低16位与运算,获得16位的有效数值。

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

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict)

真正存入元素的方法:

/**
 * 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表是否为空
    if ((tab = table) == null || (n = tab.length) == 0)
        // 初始化hash表或重新构建
        n = (tab = resize()).length;
    // 根据key的hash计算所在桶的索引
    // p为该桶的头结点
    if ((p = tab[i = (n - 1) & hash]) == null)
        // 该桶为空,直接放入桶数组位置
        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))))
            // 存入key与头结点key相同,覆盖
            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);
                    // 判断链表长度,此时binCount为7,则链长为8
                    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))))
                    // 存入key与该结点key相同,覆盖
                    break;
                // 指针移动到下一个链节点
                p = e;
            }
        }
        // e不为null,表示存入的key已经在
        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;
}

resize()

初始化哈希表或按照旧表容量的2倍扩容并重新分配元素。

/**
 * 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() {
    Node<K,V>[] oldTab = table;
    // 旧的哈希表长度
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    // 扩容阈值,默认为0
    int oldThr = threshold;
    int newCap, newThr = 0;
    if (oldCap > 0) {
        if (oldCap >= MAXIMUM_CAPACITY) {
            // hash数组的达到上限
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
   		// 新哈希表容量2倍
        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
        // 16
        newCap = DEFAULT_INITIAL_CAPACITY;
        // 12
        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;
}

这里需要注意的就是hashMap在进行扩容的时候,并不是真正地去重新计算hashCode。而是通过以下这种方式去进行计算。

(e.hash & oldCap) == 0?
将重新分配的元素key hash值和旧哈希表容量相与是什么意思呢?

假设oldCap为16,则newCap=32:

newCap(b)-1 = 11111

oldCap(b) = 10000

node1.hash = 1010010

node2.hash = 1000010

相当于两个hash的第五位和oldCap的第五位相与,node1为1,node2为0。

相与为0,则在新表中桶索引不变,00010
相与为1,则在新表中索引是10010,相比在旧表中的桶索引左移一位,增加16

public V get(Object key)

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)

/**
 * Implements Map.get and related methods
 *
 * @param hash hash for key
 * @param key the key
 * @return the node, or null if none
 */
final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    // 根据key的hash值获取桶索引
    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);
            // 链表结构,循环遍历匹配key就行了
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

treeifyBin尝试把链表转换为红黑树

  final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        //这里会进行一次判断,当整个table中的元素小于MIN_TREEIFY_CAPACITY的时候我们会去进行扩容,而不是转
        //换为红黑树,而这里的MIN_TREEIFY_CAPACITY的大小默认是为64
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null);
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }
JDK1.7JDK1.8
数据结构数组+链表数组+链表+红黑树
插入方法头插法。存在循环链表尾插法。因为采用尾插法,解决了循环链表问题
扩容机制hash&需要扩容的二进制数,所以扩容必须是2的幂扩容前所在桶索引&扩容后的容量0:当前桶1:扩容前所在桶索引+扩容后的容量(相当于所在桶索引变为之前的2倍)
线程安全问题因为采用头插法,存在环形链表的问题元素并发插入到同一位置,造成数据覆盖

Q&A:哈希表如何解决冲突?
在这里插入图片描述
Q&A为什么HashMap键值都允许为空、线程不安全、不保证有序、存储位置会变化?
在这里插入图片描述
Q&A为什么HashMap中String、Integer这样的包装类适合作为key?

在这里插入图片描述

Q&AHashMap中为什么使用红黑树而不是使用AVL(自平衡二叉查找树)树?

1、平衡性能好:
  红黑树是一种自平衡的二叉搜索树,保持了较好的平衡性能。AVL树虽然也是自平衡的,但它需要维护更为严格的平衡条件,因此在插入和删除操作时需要更多的旋转操作,而红黑树的旋转操作相对较少,性能更高。
2、复杂度较低
  红黑树的插入、删除和查找操作的时间复杂度均为O(log n),而AVL树的时间复杂度也是O(log n),但由于它的平衡条件更严格,因此需要更多的旋转操作,可能会导致性能略低。
3、实现简单
  相比于AVL树,红黑树的实现较为简单,代码量较少,容易理解和维护。
HashMap中容量的初始化
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值