我知道这是问了很多,我不知道如果我很理解哈希码,但它应该是地址,让我怎么解决我的具体的例子?如果我的理解是正确的,我有双打在我的课,但我不能将它们添加到散列码,因为重载hashCode()方法在Java中使用双重价值
possible loss of precision
found : double
required: int
return this.area();
这里是我Shape
类:
abstract class Shape implements Comparable<Shape>
{
abstract double area();
public int compareTo(Shape sh){
return Double.compare(this.area(),sh.area());
}
public int hashCode() {
return this.area();
}
public boolean equals(Shape sh) {
if (sh instanceof Shape && this.area()==sh.area()) {
return true;
} else {
return false ;
}
}
}
是area()
的唯一的价值,我需要担心hashCode()?
hashCode的行为应该与equals的行为相匹配,如果两个对象被认为相等,使用equals,那么两个对象的hashCode应该是相同的。如果您只使用形状的区域来确定它是否相等,那么您可以返回hashCode的区域。 – DanielGibbs
'Shape'是一个抽象类。你是否希望同一区域的两个形状相同,即使它们是不同的形状? – khelwood