【发布时间】:2015-02-20 20:50:44
【问题描述】:
在 equals 方法中比较双精度时,我似乎遇到了问题。我收到一条错误消息,提示 java.lang.ClassCastException: and java.lang.Double 无法转换为项目。我没有正确投射吗?当我将演员更改为 Double 时,我收到错误 cannot find symbol - method getPrice().
public class Item implements Comparable
{
private String name, category;
private int quantity;
private double price;
public Item(String nam,String cate,int quant,double pric)
{
name = nam;
category = cate;
quantity = quant;
price = pric;
}
public String toString()
{
return name + ", " + category + ", " + quantity + ", " + price;
}
public boolean equals(Object other)
{
if (price <= ((Item)other).getPrice()) // Error //
return true;
else
return false;
}
public String getName()
{
return name;
}
public String getCategory()
{
return category;
}
public int getQuantity()
{
return quantity;
}
public double getPrice()
{
return price;
}
public int compareTo(Object other)
{
int result;
double otherPrice = ((Item)other).getPrice();
String otherCategory = ((Item)other).getCategory();
if (this.equals(otherPrice))
result = category.compareTo(otherCategory);
else
result = price > otherPrice ? + 1 : price < otherPrice ? -1 : 0;
return result;
}
}
【问题讨论】:
-
Item.equals 将传递的 Object 转换为 Item,但您使用 Double 调用它,它不能转换为除 Number 和 Object 之外的任何东西。请参阅stackoverflow.com/questions/27581/… 了解如何正确实现equals 和相关问题。
-
@AngularLover 这无济于事... Java 自动装箱。
-
为什么这个问题被问了两次? stackoverflow.com/questions/28550438/…
标签: java object boolean double