【问题标题】:double cannot be dereferenced for equals and compareTo (java)double 不能取消引用 equals 和 compareTo (java)
【发布时间】: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

【问题讨论】:

  • 请使用语言标签指定语言
  • compareToequals 等方法中处理原语需要使用它们基于对象的对应项(例如Double 用于双精度)。您可以自动将原语自动装箱/拆箱到/从其对象类型中取出。比较双打时要小心...因为“平等”通常很难通过简单地使用“==”来实现。
  • 另外,boo 用于将 double 与 equals(或 ==)进行比较,并将它们用于货币。

标签: java compareto


【解决方案1】:

equals() 定义比较项目的价格,因此该行应为:

if (this.equals(other))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多