不同的值相同的 hash 值为什么会被覆盖, hashmap 不是对相同的 hash 值有链表结构处理吗
今天就来谈谈这个,这个问题在 1.7 版本和 1.8 版本中都有,分别来说说
在说之前,咱们先要达成一个共识:HashMap 发生数据覆盖的问题,是在多线程环境 & 扩容下产生的,接下来咱们具体来看
jdk 1.7
void transfer(Entry[] newTable, boolean rehash) { int newCapacity = newTable.length; for (Entry e : table) { while(null != e) { Entry next = e.next; if (rehash) { e.hash = null == e.key ? 0 : hash(e.key); } int i = indexFor(e.hash, newCapacity); e.next = newTable[i]; newTable[i] = e; // 线程 A 运行到这里时被挂起 e = next; } } }
在扩容时,发生数据覆盖问题主要核