【发布时间】:2017-09-05 13:23:31
【问题描述】:
假设我们有一些代码
class WrongHashCode{
public int code=0;
@Override
public int hashCode(){
return code;
}
}
public class Rehashing {
public static void main(String[] args) {
//Initial capacity is 2 and load factor 75%
HashMap<WrongHashCode,String> hashMap=new HashMap<>(2,0.75f);
WrongHashCode wrongHashCode=new WrongHashCode();
//put object to be lost
hashMap.put(wrongHashCode,"Test1");
//Change hashcode of same Key object
wrongHashCode.code++;
//Resizing hashMap involved 'cause load factor barrier
hashMap.put(wrongHashCode,"Test2");
//Always 2
System.out.println("Keys count " + hashMap.keySet().size());
}
}
所以,我的问题是为什么在调整 hashMap 的大小后(据我所知,这涉及 重新散列键),我们在 keySet 中仍然有 2 个键而不是 1 个(因为键对象对于两个现有的 KV 对)?
【问题讨论】:
-
实际调整大小在哪里?
-
@ACV,当我们添加第二个 KV hashMap 块时,大小变为 4 而不是 2(初始)。还是我错过了什么?
-
hashMap.keySet() 返回哈希映射中实际键的数量。所以,当你放两个键时,你总是得到 2 个。
-
您是否通过调试确认 HashMap 实际上正在调整大小?
-
@jtahlborn,是的