I need help on to override the equals
method. I have everything working except for the equals
method. The equals
method that I currently have is not giving me the correct answer. 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:This will never be true... this must be:
But I won't put any effort in coding the equals, is recommended to autogenerate equals. Something like this:
Also is highly recommended, (nearly unavoidable as @AdriaanKoster commented) when you override
equals()
method, also overridehashCode()
In
equals()
definition:Hash code: