为什么我的 java 代码中的 equals 返回 false?

Lam*_*ine 0 java equals

我不明白为什么equals()在我的代码中返回“false”而不是“true”?

class Location {

    private int x, y;

    public Location(int x, int y) {

        this.x = x;
        this.y = y;
    }
}

public class App {

    public static void main(String[] args) {

        Location a = new Location(1, 2); //
        Location b = new Location(1, 2); // same values

        System.out.println(a.equals(b)); // result : "false"
    }
}
Run Code Online (Sandbox Code Playgroud)

如何比较两个对象的值?

小智 6

用这个覆盖基本的“equals”方法:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Location that = (Location) o;
    return x.equals(that.x) &&
      y.equals(that.y);
}
Run Code Online (Sandbox Code Playgroud)