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

为什么equals在我的java代码中返回false?,java,equals,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

我不明白为什么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"
    }
}

如何比较两个对象的值?

使用以下内容覆盖基本的“等于”方法:

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

此方法在对象类中定义,以便每个Java对象都继承它。默认情况下,它的实现比较对象内存地址,因此其工作原理与==运算符相同。但是,我们可以重写此方法以定义相等对对象的意义

您应该重写该类的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);
    }
重写
equals()
方法就像一个例程。您可以使用IDE工具生成
equals()
hashcode()
方法

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Location other = (Location) obj;
        if (!getEnclosingInstance().equals(other.getEnclosingInstance()))
            return false;
        if (x != other.x)
            return false;
        if (y != other.y)
            return false;
        return true;
    }

您需要重写equals()方法。您也应该对hashcode()执行相同的操作,顺便说一句,java.awt.Point本质上与此处的类相同,但您不能对primitive
int
s执行
.equals()
,可以吗?这是不是在比8更新的java版本中引入的?我的编译器说,
不能在基本类型int上调用equals(int)
@fredrarson我想最好的做法是==then。它过去允许您使用.equals()比较早期版本中的整数。