【JavaEE】HashMap

本文深入解析HashMap的成员变量,包括size、loadFactor和threshold,阐述它们的作用和关系。初始化容量通常设置为16,当元素数量超过容量的75%时,HashMap会扩容。扩容机制确保了高效性能。同时,文章探讨了HashMap的hash方法原理,理解其散列过程对于优化数据结构至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、一些HashMap的成员变量

在这里插入图片描述其中:
size表示了map中的键值对个数

 /**
     * The number of key-value mappings contained in this map.
 */
transient int size;

loadFactor表示装载因子,用来衡量HashMap满的程度。loadFactor的默认值为0.75f。

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

threshold:临界值,当实际KV个数超过threshold时,HashMap会将容量扩容,threshold=容量*装载因子

 /**
     * 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;

capacity容量:默认最小容量是16.

 /**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

1.1 capaticty和size的区别

如下所示测试代码,测试map的size和capacity

 public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
   
        HashMap<String, String> map = new 
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值