比较两个对象始终返回 false



我正在尝试创建一个简单的日期类。我的教授还希望我们在日期类中包含我们自己的 .equals 方法,该方法应该比较两个对象。我的问题是我的方法返回 false,除非我比较完全相同的对象,即使它们的值相同。

这是我的驱动程序:

public class Lab3Driver {
    public static void main(String[] args) {
     Date theDate = new Date(6, 30, 1995);
     Date anotherDate = new Date(6, 30, 1995);
     System.out.println(theDate.equals(anotherDate));
     System.out.println(theDate);
     System.out.println(anotherDate);
    }
}

这是我的约会课:

public class Date {
    private int month;
    private int day;
    private int year;
    public Date() // default no arg constructor
    {
        this.month = 1; // set to date I completed this class, for fun.
        this.day = 26;
        this.year = 2019;
    }
    public Date(int m, int d, int y) // normal constructor in case you want to initialize variables upon object declaration
    {
        this.month = m;
        this.day = d;
        this.year = y;
    }
    public int getMonth() {
        return month;
    }
    public void setMonth(int month)
    {
        if (month >= 1 && month <= 12) // if else that checks and makes sure months are between 1 and 12
        {
            this.month = month;
        }
        else
        {
            System.out.println("Invalid month input. Months are between 1 and 12.");
        }
    }
    public int getDay()
    {
        return day;
    }
    public void setDay(int day)
    {
        if (day >= 1 && day <= 31) // if else that checks and makes sure days are between 1 and 31
        {
            this.day = day;
        }
        else
        {
            System.out.println("Invalid day input. Days are between 1 and 31.");
        }
    }
    public int getYear()
    {
        return year;
    }
    public void setYear(int year) // year can be set to anything, in the case that this program is used for something
    {                             // other than the present day, as in a reference to the past or future
        this.year = year;
    }
    public String toString() // to string in order to print out the date that is stored
    {
        String theDate = "The date is: " + this.month + "/" + this.day + "/" + this.year;
        return theDate;
    }
    public boolean equals(Object that) // compares two objects and checks for null/type casting
    {
        if (this == that)
            return true;
        else if(that == null || that.getClass()!= this.getClass())
        {
            System.out.println("Null or type casting of argument.");
            return false;
        }
        else
            return false;
    }

我认为这种方法会产生一个问题:

 public boolean equals(Object that) // compares two objects and checks for null/type casting
    {
        if (this == that)
            return true;
        else if(that == null || that.getClass()!= this.getClass())
        {
            System.out.println("Null or type casting of argument.");
            return false;
        }
        else
            return false;
    }

这很正常,因为你写了

else {
   return false;
}

因此that每当对象具有不同的引用并且来自同一类时,您就会进入上面的 else 语句,该语句返回 false。您应该实现代码而不是返回 false,例如:

public boolean equals(Object that) // compares two objects and checks for null/type casting
{
    if (this == that)
        return true;
    else if(that == null || that.getClass()!= this.getClass())
    {
        System.out.println("Null or type casting of argument.");
        return false;
    }
    else
        return this.year == that.getYear() && ...;
}
if (this == that)

此行不比较对象。这只验证你的对象是否在同一个内存空间中,基本上是询问它是否是完全相同的对象(指向同一个地方)。

如果要比较两个不同的对象,则两个不同的实例,例如

Date theDate = new Date(6, 30, 1995);
Date anotherDate = new Date(6, 30, 1995);

然后,您必须添加更多代码行来检查每个对象中每个变量中的每个值,或者重写" == "方法以使其比较值。

> Sοme οther things tο nοte:

正如 Nate 已经说过的,yοu 有 tο cοmpare 各个字段 οf twο οbjects yοu 正在 cοmparing。Tο dο that, yοu 可以使用return year == that.getYear() && day == that.getDay() && mοnth == that.getMοnth() .

但是等等!Yοur equals methοd 收Object .因此,我们不能使用thοse methοds。有 twο 种方法可以解决这个问题。

  1. Dο instanceοf在开始检查 οf 甲基οd,然后将参数 tο 转换为Date οbject。
  2. 限制参数 οf yοur methοd tο οnly allοw Date οbjects.

从本质上讲,我选择后者,因为如果 yοu 使用 nοn- Date οbject,errοr 将在 cοmpile 时间 pοp 上升。Hοwever,如果 yοu 在 methοd 中进行了类型检查,如果类型检查失败,则 yοu 可能永远不会出错,如果 yοu 提交了一个参数,该参数在调用该方法之前不是Date οbject。

您需要确保如果重写 equals 方法,您也应该覆盖 hashCode 方法。

供您参考,请阅读该部分https://www.baeldung.com/java-equals-hashcode-contracts#hashcode

我已经为您完成了两种覆盖的方法。

    @Override
    public boolean equals(Object that) {
        if (this == that)
            return true;
        
        if(!(that instanceof Date))
            return false;
        
        if(that == null || that.getClass()!= this.getClass())
            return false;
        
        Date anotherDate = (Date) that;
        if(this.month == anotherDate.month
                && this.day == anotherDate.day
                && this.year == anotherDate.year)
            return true;
        
        return false;
    }
    @Override
    public int hashCode() {
        
        final int prime = 31;
        int result = 1;
        result = prime * result + (int) (month ^ (month >>> 16));
        result = prime * result + (int) (day ^ (day >>> 16));
        result = prime * result + (int) (year ^ (year >>> 16));
        
        return result;
    }

相关内容

  • 没有找到相关文章