JDK容器与并发—Map—IdentityHashMap

本文详细探讨了IdentityHashMap的性能特点、参数影响、适用场景及迭代器特性,包括容量调整策略、解决hash碰撞的方法及备份数据的应用案例。同时介绍了其内部数据结构和关键方法实现,特别强调了其fail-fast的迭代器机制。

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

概述

      基于数组,用==比较key的类HashMap,非线程安全。

1)在System#identityHashCode哈希合理情况下,基础操作get、put等为固定时间;

2)影响性能的参数:期望最大键值对数(即键值对threshold),该参数在初始化时决定bucket数。如果map中的键值对数超过了该参数,bucket数则增长,进一步导致rehash;另外,容器视图迭代器遍历时间与bucket数成比例,如果对迭代性能或内存成本有较高要求,该参数不应该设置过大。

3)适用于做备份数据:保留拓扑结构象图转化、保留代理对象,都用到了对象的唯一性;

4)迭代器fail-fast。

数据结构

      Object数组,逻辑上是环形的。长度为2的幂次方,table[i]为key,table[i+1]为该key关联的value,其中i为偶数。

private transient Object[] table;

构造器

      了解几个概念:最大键值对:table.length/2; 默认负载因子:2/3; 期望最大键值对数:最大键值对*负载因子,达到该值则rehash。

// 无参构造,采用默认最大键值对数32,键值对阈值为21
public IdentityHashMap() {
	init(DEFAULT_CAPACITY);
}

// 带期望最大键值对数构造
public IdentityHashMap(int expectedMaxSize) {
	if (expectedMaxSize < 0)
		throw new IllegalArgumentException("expectedMaxSize is negative: "
										   + expectedMaxSize);
	init(capacity(expectedMaxSize));
}

// 带Map参数构造
public IdentityHashMap(Map<? extends K, ? extends V> m) {
	// Allow for a bit of growth
	this((int) ((1 + m.size()) * 1.1));
	putAll(m);
}

增删改查

容量调整策略

      与HashMap大致相同:

1)当IdentityHashMap中键值对数达到键值对阈值则对其table进行容量调整 ,table容量翻倍;
2)table最大容量为1 << 30,即最大键值对数为MAXIMUM_CAPACITY = 1 << 29;
3)table容量达到最大后,如果有resize请求,则仅仅将键值对阈值调整为MAXIMUM_CAPACITY-1,不会产生新的table,还可以继续添加新的键值对,之后如果再有resize请求,则会抛出容量异常;
4)若table resize过程中产生新的table,需要将旧table的键值对重新在新table中确定bucket,再添加进来,也就是所说的hash table rehash。

private void resize(int newCapacity) {
	// assert (newCapacity & -newCapacity) == newCapacity; // power of 2
	int newLength = newCapacity * 2;

	Object[] oldTable = table;
	int oldLength = oldTable.length;
	if (oldLength == 2*MAXIMUM_CAPACITY) { // can't expand any further
		if (threshold == MAXIMUM_CAPACITY-1)
			throw new IllegalStateException("Capacity exhausted.");
		threshold = MAXIMUM_CAPACITY-1;  // Gigantic map!
		return;
	}
	if (oldLength >= newLength)
		return;

	Object[] newTable = new Object[newLength];
	threshold = newLength / 3; // 键值对负载因子依然为2/3,threshold几乎翻倍

	// rehash
	for (int j = 0; j < oldLength; j += 2) {
		Object key = oldTable[j];
		if (key != null) {
			Object value = oldTable[j+1];
			oldTable[j] = null;
			oldTable[j+1] = null;
			int i = hash(key, newLength); // 在newTable中获取bucketIndex
			while (newTable[i] != null) // 解决hash碰撞
				i = nextKeyIndex(i, newLength); // 循环后移2位
			newTable[i] = key;
			newTable[i + 1] = value;
		}
	}
	table = newTable;
}

private static int hash(Object x, int length) {
	// 不管x有无Override Object的hashCode方法,都会返回原始的Object的hashCode值
	int h = System.identityHashCode(x); 
	// Multiply by -127, and left-shift to use least bit as part of hash
	return ((h << 1) - (h << 8)) & (length - 1);
}

// 循环右移2位
private static int nextKeyIndex(int i, int len) {
	return (i + 2 < len ? i + 2 : 0);
}

增、改

      与HashMap相似,步骤:

1)根据System.identityHashCode(key)获取hash码;
2)用hash码确定bucketIndex;
3)先遍历bucket中键值对,确定是否已有==key的,有则替换新value后返回;否则将key—value对用数组的方式添加进来。

public V put(K key, V value) {
	Object k = maskNull(key);
	Object[] tab = table;
	int len = tab.length;
	int i = hash(k, len); // 确定bucketIndex

	Object item;
	while ( (item = tab[i]) != null) {
		if (item == k) { // 用==判断key是否相同
			V oldValue = (V) tab[i + 1];
			tab[i + 1] = value;
			return oldValue;
		}
		i = nextKeyIndex(i, len);
	}

	modCount++;
	tab[i] = k;
	tab[i + 1] = value;
	if (++size >= threshold)
		resize(len); // len == 2 * current capacity.
	return null;
}

步骤:
1)根据System.identityHashCode(key)获取hash码;
2)用hash码确定bucketIndex;
3)遍历bucket中键值对,确定是否已有==key的,有则删除且对其后的键值对进行rehash,否则返回null

public V remove(Object key) {
	Object k = maskNull(key);
	Object[] tab = table;
	int len = tab.length;
	int i = hash(k, len);

	while (true) {
		Object item = tab[i];
		if (item == k) {
			modCount++;
			size--;
			V oldValue = (V) tab[i + 1];
			tab[i + 1] = null;
			tab[i] = null;
			closeDeletion(i); // 因删除产生的rehash
			return oldValue;
		}
		if (item == null)
			return null;
		i = nextKeyIndex(i, len);
	}

}

// 对所删除键值对后的键值对进行rehash
private void closeDeletion(int d) {
	// Adapted from Knuth Section 6.4 Algorithm R
	Object[] tab = table;
	int len = tab.length;

	// Look for items to swap into newly vacated slot
	// starting at index immediately following deletion,
	// and continuing until a null slot is seen, indicating
	// the end of a run of possibly-colliding keys.
	Object item;
	for (int i = nextKeyIndex(d, len); (item = tab[i]) != null;
		 i = nextKeyIndex(i, len) ) {
		// The following test triggers if the item at slot i (which
		// hashes to be at slot r) should take the spot vacated by d.
		// If so, we swap it in, and then continue with d now at the
		// newly vacated i.  This process will terminate when we hit
		// the null slot at the end of this run.
		// The test is messy because we are using a circular table.
		int r = hash(item, len);
		if ((i < r && (r <= d || d <= i)) || (r <= d && d <= i)) {
			tab[d] = item;
			tab[d + 1] = tab[i + 1];
			tab[i] = null;
			tab[i + 1] = null;
			d = i;
		}
	}
}

步骤:
1)根据System.identityHashCode(key)获取hash码;
2)用hash码确定bucketIndex;
3)遍历bucket中键值对,确定是否已有==key的,有则返回关联的value,否则返回null

public V get(Object key) {
	Object k = maskNull(key);
	Object[] tab = table;
	int len = tab.length;
	int i = hash(k, len);
	while (true) {
		Object item = tab[i];
		if (item == k)
			return (V) tab[i + 1];
		if (item == null)
			return null;
		i = nextKeyIndex(i, len);
	}
}

迭代器

      利用数组特性遍历,IdentityHashMapIterator为基础迭代器,其删除过程中需要对其后的键值对rehash。

特性

解决hash碰撞
1)IdentityHashMap的table数组的长度为2的幂次方;
2)根据System.identityHashCode(key)获取hash码,用hash码确定bucketIndex;
3)用数组解决hash碰撞问题。

      其与HashMap解决hash碰撞的方式是不一样的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值