对于equals和compareTo(java),无法取消对double的引用
这里有个问题。我得到一个编译错误,说double不能被解引用。我知道double是基元类型的,但我仍然不完全理解如何在compareTo方法中使用它们。那么在重写equals方法之后,我如何在compareTo方法中使用它呢?我想先比较一下价格。如果价格等于其他价格,则接下来必须比较类别 定义的equals()比较项目的价格,因此该行应为:对于equals和compareTo(java),无法取消对double的引用,java,compareto,Java,Compareto,这里有个问题。我得到一个编译错误,说double不能被解引用。我知道double是基元类型的,但我仍然不完全理解如何在compareTo方法中使用它们。那么在重写equals方法之后,我如何在compareTo方法中使用它呢?我想先比较一下价格。如果价格等于其他价格,则接下来必须比较类别 定义的equals()比较项目的价格,因此该行应为: public class Item implements Comparable { private String name, category;
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
需要使用基于对象的对应项(例如Double
表示Double)。可以自动将基本体与它们的对象类型进行自动装箱/取消装箱。比较双倍时要小心。。。由于简单地使用“==”通常很难实现“相等”。此外,boo用于比较双倍与等于(或=
),并将其用于货币。可能的
if (this.equals(other))