double不能取消引用equals和compareTo(java)

时间:2015-02-16 21:12:22

标签: java compareto

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方法中使用它?我想首先比较价格。如果价格等于 otherPrice ,则必须先比较类别

1 个答案:

答案 0 :(得分:-1)

定义的

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

if (this.equals(other))