简体   繁体   English

equals方法-如何覆盖

[英]equals method - how to override

I need help on to override the equals method. 我需要帮助来覆盖equals方法。 I have everything working except for the equals method. 除了equals方法之外,我已完成所有工作。 The equals method that I currently have is not giving me the correct answer. 我目前拥有的equals方法无法给我正确的答案。 I can not seem to figure out what could be the problem. 我似乎无法弄清楚可能是什么问题。

My Class: 我的课:

package myclasses;

public class Currency
{
    private int dollars, cents;

    public Currency()
    {
        dollars = 0;
        cents = 0;
    }

    public Currency(int d, int c)
    {
        this.dollars = d;
        this.cents = c;

        setCents(cents);
    }

    public int getDollars()
    {
        return dollars;
    }

    public int getCents()
    {
        return cents;
    }

    private void setDollars(int dollars)
    {
        this.dollars = dollars;
    }

    private void setCents(int cents)
    {       
        while(cents > 99)
        {
            cents = (cents - 100);
            dollars++;
        }

        this.cents = cents;
    }

    public void setAmount(int newDollars, int newCents)
    {
        setDollars(dollars);
        setCents(cents);
    }

    public void add(int dollars, int cents)
    {
        this.dollars =  dollars + getDollars();
        cents = cents + getCents();

        setCents(cents);
    }

    public boolean equals(Object dollars, Object cents)
    {
        if(this == dollars && this == cents)
            return true;

        if(!(dollars instanceof Currency) || !(cents instanceof Currency))
            return false;

        Currency money = (Currency) dollars;
        Currency penny = (Currency) cents;

        return (this.dollars == money.dollars) && (this.cents == penny.cents);
        //return Currency.dollars.equals(Currency.cents);
        //return this.equals(dollars) && this.equals(cents);

    }

    public boolean isZero()
    {
        if(getDollars() == 0 && getCents() == 0)
        {
            return true;
        }
        return false;
    }

    public String toString()
    {
        return "$" + getDollars() + "."   +
                (getCents() < 10 ? ("0" + getCents()) : getCents());
    }
}

Your equals() method has some errors like: 您的equals()方法有一些错误,例如:

if(this == dollars && this == cents)

This will never be true... this must be: 这将永远是不正确的...这必须是:

if(this.dollars == dollars && this.cents == cents)

But I won't put any effort in coding the equals, is recommended to autogenerate equals. 但是我不会花任何精力编写等值代码,建议自动生成等值代码。 Something like this: 像这样:

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Currency other = (Currency) obj;
    if (cents != other.cents)
        return false;
    if (dollars != other.dollars)
        return false;
    return true;
}

Also is highly recommended , (nearly unavoidable as @AdriaanKoster commented) when you override equals() method, also override hashCode() 强烈建议 ,(当您重写equals()方法时,也不可避免地要使用@AdriaanKoster进行注释),同时也重写hashCode()
In equals() definition: equals()定义中:

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes. 请注意,通常有必要在重写此方法时重写hashCode方法,以维护hashCode方法的常规协定,该协定规定相等的对象必须具有相等的哈希码。

Hash code: 哈希码:

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + cents;
    result = prime * result + dollars;
    return result;
}

I'm not quite sure why you are going the first check in your equals method. 我不太确定为什么要在equals方法中进行第一次检查。 But I'll tell you how I am usually doing my equals method 但我会告诉你我通常如何做equals方法

public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    } else if (obj == null) {
        return false;
    } else if (getClass() != obj.getClass()) {
        return false;
    }

    //a cast of object to the class you are using should be here
    if (this.someField.equals(castObject.someField)
            && this.otherField.equals(castObject.otherField)) {
        return true;
    }

    return false;
}

So here's what's happening. 所以这就是正在发生的事情。 The first part of the method does basic checks - whether the object that you are testing is the same as the parameter, whether the object is null, and whether they are from the same class. 该方法的第一部分进行基本检查-测试的对象是否与参数相同,该对象是否为null,以及它们是否来自同一类。 Note that they are else if's because there are more than just those 3 cases. 请注意,它们是if,因为不止这3种情况。

If you've not entered any of the 3 initial conditional statements, you will need to make a cast of the obj parameter to the class that you are in. You are safe to do so because of the last if - 如果您没有输入3个初始条件语句中的任何一个,则需要将obj参数转换为您所在的类。您可以这样做,因为最后一个-

else if (getClass() != obj.getClass()) {
    return false;
} 

After that simply define the rule by which you determine whether two objects are the same. 之后,只需定义规则即可确定两个对象是否相同。 In the example that I'm using, I'm checking the contents of two fields of the class. 在我使用的示例中,我正在检查类的两个字段的内容。 If they are the same, then the objects are equal. 如果它们相同,则对象相等。

If you are overriding equals method, then your above code is not correctly overriding equals method. 如果您要覆盖equals方法,则您上面的代码未正确覆盖equals方法。

use below code instead for overriding equals-- 用下面的代码代替等于

public boolean equals(Object currency) {

Currency newref = null;

if (currency instanceof Currency) {
  newref = (Currency)currency;
}
return (this.dollars == newref.dollars) && (this.cents == newref.cents);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM