【发布时间】:2015-02-16 21:12:22
【问题描述】:
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())
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;
String otherPrice = ((Item)other).getPrice();
String otherCategory = ((Item)other).getCategory();
if (price.equals(otherPrice)) //Problem Here
result = category.compareTo(otherCategory);
else
result = price.compareTo(otherPrice);
return result;
}
}
-------------------------------
在点//这里有问题。我收到编译错误,说不能取消引用双打。我知道双打属于原始类型,但我仍然不完全了解如何在 compareTo 方法中使用它们。那么重写equals方法后,怎么在compareTo方法中使用呢?我想先比较价格。如果 price 等于 otherPrice,则接下来必须比较 category。
【问题讨论】:
-
请使用语言标签指定语言
-
在
compareTo和equals等方法中处理原语需要使用它们基于对象的对应项(例如Double用于双精度)。您可以自动将原语自动装箱/拆箱到/从其对象类型中取出。比较双打时要小心...因为“平等”通常很难通过简单地使用“==”来实现。 -
另外,boo 用于将 double 与
equals(或==)进行比较,并将它们用于货币。