Avi*_*Avi -1 java methods equals
我需要帮助来覆盖该equals方法.除了这个equals方法,我的一切都在工作.equals我目前拥有的方法并没有给我正确的答案.我似乎无法弄清楚可能是什么问题.
我的课:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
您的equals()方法有一些错误,如:
if(this == dollars && this == cents)
Run Code Online (Sandbox Code Playgroud)
这永远不会是真的......这必须是:
if(this.dollars == dollars && this.cents == cents)
Run Code Online (Sandbox Code Playgroud)
但我不会在编码等于中做任何努力,建议自动生成等于.像这样的东西:
@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;
}
Run Code Online (Sandbox Code Playgroud)
也强烈建议,(几乎是无法避免的@AdriaanKoster评论)当你重写equals()方法,还覆盖hashCode()
在equals()定义:
请注意,通常需要在重写此方法时覆盖hashCode方法,以便维护hashCode方法的常规协定,该方法声明相等对象必须具有相等的哈希代码.
哈希码:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + cents;
result = prime * result + dollars;
return result;
}
Run Code Online (Sandbox Code Playgroud)