初识HashMap

HashMap

官方介绍

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.)

  • HashMap 和Hashtable 差不多
  • HashMap 是线程不安全的 – it is unsynchronized
  • HashMap 允许key与value为null – permits nulls

As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs.
The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
static final int MAXIMUM_CAPACITY = 1 << 30;

  • 默认初始大小 – default initial capacity : 16
  • 负载因子 – load factor : 0.75

/**
* Constructs a new, empty hashtable with a default initial capacity (11)
* and load factor (0.75).
*/
public Hashtable() {
this(11, 0.75f);
}
//此处做对比
//Hashtable 的 初始大小为11,负载因子也是0.75

存储过程

  1. public native int hashCode();
    • 调用这个方法会生成一个int型的整数,我们叫它哈希码。
    • 通过hashcode定位到要存储在数组的哪里,通过hashcode值和数组长度取模我们可以得到元素存储的下标。
  2. 若数组下面有值,再用equal()方法,如果不等则在原元素下面使用链表的结构存储该元素,相等则直接覆盖。
    在这里插入图片描述
    3.HashMap的key、value可以为null,不过只能有一个key为null,但可以有多个null的value。

java1.7 之前是数组+链表 ,之后是 数组+链表+红黑树。
如果链表长度大于8且节点数组长度大于64的时候,就把链表下所有的节点转为红黑树。
树形化还有一个要求就是数组长度必须大于等于64,否则继续采用扩容策略

未完待续…

参考:
HashMap 详解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值