hashCode()与equals()必须同时复写,
成对出现,复写equals必须复写hashCode,否则会造成Map、Set等异常。
如通过put覆盖原map中的键值对,但如果只复写了equals,会造成map.gey(existKey)返回为null,从而map里出现多个同样的key,进一步造成内存溢出。因此,必须同时复写hashCode,使map.gey(existKey) -> value
实验如下:
static class Cluster {
String name = null;
int hostCnt = 0;
String type = null;
Cluster(String name, int hostCnt, String type) {
this.name = name;
this.hostCnt = hostCnt;
this.type = type;
}
@Override
public boolean equals(Object other) {
return (other instanceof Cluster) && this.name.equals(((Cluster)other).name) && this.hostCnt == ((Cluster)other).hostCnt;
}
@Override
public int hashCode() {
return this.name.hashCode() + this.hostCnt;
}
}
public static void main(String[] args) throws Exception {
Cluster c1 = new Cluster("cluster1", 100, "store");
Cluster c2 = new Cluster("cluster1", 100, "search");
Cluster c3 = new Cluster("cluster2", 40, "store");
Set<Cluster> clusters = new HashSet<>();
clusters.add(c1);
clusters.add(c2);
clusters.add(c3);
System.out.println(clusters.size()); // 不重载hashCode(),输出为3,重载后,输出为2
clusters.stream().forEach(c -> System.out.println(c.name + ", " + c.hostCnt + ", " + c.type));
}
本文解释了hashCode()与equals()方法的重要性及如何正确地同时复写这两个方法,以避免在使用Map和Set等集合时出现问题。并通过实例演示了如果不正确复写hashCode()可能导致的内存溢出风险。
1740

被折叠的 条评论
为什么被折叠?



