gpt4 book ai didi

java - HashSet contains() 为自定义对象返回 false。 hashCode() 和 equals() 似乎实现正确

转载 作者:搜寻专家 更新时间:2023-11-01 04:01:57 26 4
gpt4 key购买 nike

我有以下简单的 Rectangle 类。如果两个矩形具有相同的高度和宽度,则它们是相等的并且具有相同的哈希码。我向 hashSet 添加了一个新的矩形。

Set<Rectangle> set = new HashSet<Rectangle>();
set.add(new Rectangle(3,3));

当我尝试在具有相同高度和宽度的新矩形上调用 contains 时,它返回 false。

set.contains(new Rectangle(3,3)) 返回 false。我不知道为什么。有什么想法吗?

   public class Rectangle implements Comparable<Rectangle> {
final int height, width, area, minimumEdge, maximumEdge;

public Rectangle(int height, int width) {
this.height = height;
this.width = width;
area = height * width;
maximumEdge = height > width ? height : width;
minimumEdge = height < width ? height : width;
}

public int compareTo(Rectangle rect2) {
if (rect2.minimumEdge > this.minimumEdge) {
return -1;
} else if (rect2.minimumEdge < this.minimumEdge) {
return 1;
} else {
return 0;
}
}

public int hashCode(){
return ((width + height)*31);
}

public boolean equals(Rectangle rect2){
return (this.height == rect2.height && this.width == rect2.width);
}
}

最佳答案

您实际上并没有覆盖 equals()

您创建了一个新的equals(Rectangle) 方法,它与虚拟equals(Object) 方法无关。

这就是为什么在尝试覆盖方法时应始终添加 @Override 的原因。

关于java - HashSet contains() 为自定义对象返回 false。 hashCode() 和 equals() 似乎实现正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18555042/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com