首页 > 解决方案 > 用 '==' 比较两个对象实际上有什么作用?

问题描述

好久没来这里发帖了,如有错误请见谅。

我正在从 MOOC fi 学习 java。我目前在第 5 周,这里提到要比较两个对象,您必须执行以下操作:

public class SimpleDate {
    private int day;
    private int month;
    private int year;

    public SimpleDate(int day, int month, int year) {
        this.day = day;
        this.month = month;
        this.year = year;
    }

    public boolean equals(Object compared) {
        // if the variables are located in the same position, they are equal
        if (this == compared) {
            return true;
        }

        // if the type of the compared object is not SimpleDate, the objects are not equal
        if (!(compared instanceof SimpleDate)) {
            return false;
        }

        // convert the Object type compared object
        // into a SimpleDate type object called comparedSimpleDate
        SimpleDate comparedSimpleDate = (SimpleDate) compared;

        // if the values of the object variables are the same, the objects are equal
        if (this.day == comparedSimpleDate.day &&
            this.month == comparedSimpleDate.month &&
            this.year == comparedSimpleDate.year) {
            return true;
        }

        // otherwise the objects are not equal
        return false;
    }

    @Override
    public String toString() {
        return this.day + "." + this.month + "." + this.year;
    }
}

所以我很困惑,什么是:

public boolean equals(Object compared) {
    // if the variables are located in the same position, they are equal
    if (this == compared) {
        return true;
    }

上面的代码究竟是做什么的?位于同一位置是什么意思?

仅检查对象是否属于特定类类型然后比较它们的实例变量以查看它们是否相等不是更好吗?

标签: java

解决方案


this并且compared在您的情况下都是对对象的引用。

在 Java 中,每个对象都驻留在特定的内存位置。两个不同的对象不能同时具有相同的内存位置。

相等运算符或“==”根据它们是否位于相同的内存地址来比较两个对象。所以“==”操作符只有当它比较的两个对象引用代表完全相同的对象时才会返回true,否则“==”将返回false。

另请注意,==运算符equals与类上的方法不同。

您可以阅读更多内容:https ://javarevisited.blogspot.com/2012/12/difference-between-equals-method-and-equality-operator-java.html#ixzz79Ev3iZ5P


推荐阅读