JDK 1.7 HashMap 源码分析
Java 面试 大约 1319 字数据结构
数组 + 单链表
哈希冲突解决方法
头插方式
void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}
null key
空键插入到数组索引0
的位置上。
private V putForNullKey(V value) {
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(0, null, value, 0);
return null;
}
扩容
扩容为原始数组的2
倍。
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
Entry[] newTable = new Entry[newCapacity];
// 赋值给新的数组
transfer(newTable, initHashSeedAsNeeded(newCapacity));
table = newTable;
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
阅读 1859 · 发布于 2021-10-14
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Java 无法 debug Finalizer 类阅读 216
-
Redis 最大内存策略阅读 1708
-
Android ContentProvider批量插入数据阅读 4116
-
Java LockSupport 几种唤醒机制阅读 26
-
设计模式之建造者模式阅读 1723
-
Arthas 使用 logger 不停机更新 Spring Boot logback 日志等级阅读 3676
-
Java jdbc 批处理 rewriteBatchedStatements=true阅读 3041
-
Vue No module factory available for dependency type: CssDependency阅读 775
-
设计模式之迭代器模式阅读 2615
-
为什么 Redis 的 hash slot 设置为 16384阅读 2591