有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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);
            }
        }

共 (2) 个答案

  1. # 1 楼答案

    实际上,您还没有覆盖equals()

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

    这就是为什么在尝试重写方法时总是要添加@Override

  2. # 2 楼答案

    这里:

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

    您可以创建自己的equals方法,而不是override superclass方法

    你必须这样写:

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Rectangle rect2 = (Rectangle) obj;
        return (this.height == rect2.height && this.width == rect2.width);
    }