HashMap1.7源码详解

概述

本文主要分析HashMap类的源码

HashMap继承结构

public class HashMap<K,V>
    extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable
{
  

HashMap继承结构图

可以看到:

1、实现了 Map 接口,拥有一组map的通用操作

2、实现了 Cloneable 接口,可进行拷贝,需要注意的是 hashmap 是浅拷贝,修改拷贝对象对源对象会产生影响

3、实现了 Serializable 接口,实现了序列化,可保存于本地

HashMap的数据结构

数组 + 单向链表

HashMap的成员变量

    /**
     * The default initial capacity - MUST be a power of two.
     * 默认初始容量
     */
    static final int DEFAULT_INITIAL_CAPACITY = 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.
     * 最大容量
     */
    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 table, resized as necessary. Length MUST Always be a power of two.
     * 用来存储键值对的Entry数组
     */
    transient Entry<K,V>[] table;

    /**
     * The number of key-value mappings contained in this map.
     * 实际的元素个数
     */
    transient int size;

    /**
     * The next size value at which to resize (capacity * load factor).
     * 阈值 = capacity(容量)* loadFactor(负载因子。这个值是当前已占用数组长度的最大值。size 超过这个值就重新 resize(扩容),
     * 扩容后的 HashMap 容量是之前容量的两倍。默认的临界值是12 = 16 * 0.75
     */
    int threshold;

    /**
     * The load factor for the hash table.
     * 哈希表的负载因子,默认是0.75f
     */
    final float loadFactor;

    /**
     * 每次扩容和更改 map 结构的计数器
     */
    transient int modCount;

Entry必须要介绍一下,看源码

    static class Entry<K,V> implements Map.Entry<K,V> {
        fina
  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值