如何使两个对象在 Hashset 的 contains 方法中相等

How to make two objects equal in contains method of Hashset

我创建了一个 Pair Class,它有下面提到的 3 个变量,并覆盖了 equals 方法,并假设它用于包含 hashset 的方法。但事实并非如此。有人可以解释在 Pair class 中要实现什么以确保它只等于 x 和 y 的值。

Class Pair extends Object {
int x;
int y;
int dis;
   public Pair(int x, int y, int d) {
    this.x = x;
    this.y = y;
    this.dis = d;
   }
  @override
  public boolean equals(Pair p) {
  return this.x == p.x && this.y == p.y
  }
}

每当您覆盖 equals 时,您也应该覆盖 hashCode:

@Override
public int hashCode() {
    return Objects.hash(x,y);
}

参见equalshashCode的总合同: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html

通常需要在重写equals方法时重写hashCode方法,以维护hashCode方法的通用契约,即相等的对象必须具有相等的哈希码.

import java.util.HashSet;

class Point extends Object {
    int x, y, dis;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
        this.dis = (int) Math.sqrt(x * x + y * y);
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof Point) {
            Point p = (Point) o;
            return p.x == x && p.y == y;
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }
}

public class Equals {
    public static void main(String[] args) {
        HashSet<Point> set = new HashSet<Point>();
        set.add(new Point(1, 2));
        set.add(new Point(1, 2));
        set.add(new Point(1, 3));
        System.out.println(set.size());
    }
}

参见 equals API 文档