【发布时间】:2017-05-16 10:02:32
【问题描述】:
我在下面的课程中发现了 hashmap 的一些奇怪行为。
class Employee {
private String a;
private int b;
public Employee(String a, int b) {
this.a = a;
this.b = b;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((a == null) ? 0 : a.hashCode());
result = prime * result + b;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (a == null) {
if (other.a != null)
return false;
} else if (!a.equals(other.a))
return false;
if (b != other.b)
return false;
return true;
}
public static void main(String[] args) {
HashMap<Employee,Integer> map = new HashMap<>();
for(int i = 0; i < 13; i++) {
map.put(new Employee( i + "", i), i + i);
}
}
}
当我使用 new Employee("", i) 作为在地图中存储数据的键时,它工作正常并在第 12 个节点插入后调整地图大小。但在使用 new Employee(i+"", i) 作为键,它表现出奇怪的行为,在使用此键添加第 10 个元素时,它将映射的大小从 16 调整为 32,在添加第 11 个元素时,它再次将映射的大小从 32 调整为 64。 如果您发现此行为的任何原因,请提供帮助。
【问题讨论】:
-
您如何观察这种行为?用调试器?您可能在谈论内部大小而不是地图中的实际条目数,对吧?
-
是的,在调试模式下,您可以检查添加第 10 个元素时它的大小从 16 调整到 32...