- 4
- 0
- 约1.01万字
- 约 10页
- 2019-04-17 发布于广东
- 举报
剖析Java中HashMap数据结构的源码及其性能优化
这篇文章主要介绍了 Java中HashMap数据结构的源码及其性能优化,文中以Java 8后 HashMap的性能提升來讨论了 HashMap的一些优化点,需要的朋友可以参考下
存储结构
首先,HashMap是基于哈希表存储的。它内部有一个数组,当元素要存储的时候,先计算 其key的哈希值,根据哈希值找到元素在数组中对应的下标。如杲这个位置没有元素,就直 接把当前元素放进去,如果有元素了(这里记为A),就把当前元素链接到元素A的前面,然 后把当前元素放入数组屮。所以在Hashmap 数组其实保存的是链表的首节点。下面是 百度百科的一张图:
EntryEntryEntryKeyKeyEntryValueValueEnttyEntryEntryEntryEnttyEntryEntry
Entry
Entry
Entry
Key
Key
Entry
Value
Value
Entty
Entry
Entry
Entry
Entty
Entry
Entry
如上图,每个元素是一个Entry对象,在其屮保存了元素的key和value,还有一个指针可用 于指向下一个对象。所有哈希值相同的key(也就是冲突了)用链表把它们串起来,这是拉链 法。
内部变量
〃默认初始容量
static final int DEFAULT_INITIAL_CAPACITY = 16;
〃最大容量
static final int MAXIMUM_CAPACITY = 1? 30;
〃默认装载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
〃哈希表
transient EntryK,V[] table;
〃键值对的数量 transient int size;
〃扩容的阈值
int threshold;
〃哈希数组的装载因子
final float loadFactor;
在上面的变量中,capacity是指哈希表的长度,也就是table的大小,默认为16。装载因子 loadFactor是哈希表的“装满程度”,JDK的文档是这样说的:
The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically in creased ? Whe n the number of en tries in the hash table exceeds the product of the load factor and the curr ent capacity, the hash table is rehashed (that is, in ter nal data structures are rebuilt) so that the hash table has approximately twice the number of buckets? 大体意思是:装载因子是哈希表在扩容之前能装多满的度量值。当哈希表中“键值对”的数 量超过当前容M(capacity)和装载因子的乘积后,哈希表重新散列(也就是内部的数据结构重 建了),并且哈希表的容量大约变为原来的两倍。
从上面的变量定义可以看出,默认的装载因子DEFAULT_LOAD_FACTOR是0.75。这个值越大, 空间利用率越高,但查询速度(包括get和put)操作会变慢。明白了装载因子之后,threshold 也就能理解了,它其实等于容量*装载因子。
构造器
public HashMap(int initialCapacity, float loadFactor) {
if (initialcapacity 0)
throw new HlegalArgumentException(lllegal initial capacity: + initialcapacity);
if (initialCapacity MAXIMUM_CAPACITY) initialcapacity = MAXIMUM_CAPACITY;
if (loadFactor = 0 11 Float.isNaN(loadFactor))
throw new HlegalArgumentExcepti on (Illegal load factor: + loadFactor);
// Find a power of 2 = initialcapacity
int capacity = 1;
while (capacity initialcapacity) //计算出大于指定容量的最
原创力文档

文档评论(0)