【发布时间】:2019-07-08 06:19:07
【问题描述】:
我编写了下面的代码来测试当所有元素都在同一个桶中结束时 hashmap 的行为:-
public class DerivedMain {
int data = 10;
@Override
public int hashCode() {
return data;
}
public static void main(String[] args) {
HashMap m = new HashMap();
for(int i=0;i<20;i++) {
m.put(i, i);
}
Field tableField = null;
try {
tableField = HashMap.class.getDeclaredField("table");
} catch (NoSuchFieldException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tableField.setAccessible(true);
Object[] table = null;
try {
table = (Object[]) tableField.get(m);
} catch (IllegalArgumentException | IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(table == null ? 0 : table.length);
}
}
我得到以下输出:- 32
为什么即使所有元素都在同一个存储桶中结束,也会发生大小调整?
【问题讨论】:
标签: java reflection hashmap hashtable