重写equals方法以接受Object类内部的doubles.Java语言



在比较equals方法内部的doubles时,我似乎遇到了一个问题。我收到一个错误,说java.lang.ClassCastException: and java.lang.Double无法转换为Item。我选角不对吗?当我将转换更改为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;
    }
}

我假设传递到compareTo-method的另一个是Item。

所以你有一个项目other,和一个双倍的otherPrice。

然后,当您在if语句中调用this.equals(otherPrice)时,您正在执行Item.equals(Double).

您应该传入一个项目。我想你想用ObjectotherPrice = ((Item)other); 取代double otherPrice = ((Item)other).getPrice();

看看你是否将一个double传递到equals方法中——你试图将这个double强制转换为Item,这是不正确的。

您的问题在于compareTo方法。您正试图将项目对象与替身进行比较。你的方法应该是这样的:

public int compareTo(Object other) {
    int result;
    double otherPrice = ((Item) other).getPrice();
    String otherCategory = ((Item) other).getCategory();
    if (this.price==otherPrice)
        result = category.compareTo(otherCategory);
    else
        result = price > otherPrice ? +1 : price < otherPrice ? -1 : 0;
    return result;
}

注意Java中的equals方法将Object作为参数。对于compareTo方法也是如此。这意味着参数可以是任何类型(String、List、Double…)。我怀疑这就是这里发生的情况。

equals方法中,将参数other强制转换为Item。但是如果other不是Item呢?

在使用instanceof操作符进行强制转换之前,您应该检查other的类型,如下所示:

public boolean equals(Object other) {
    if (!(other instanceof Item)) { //this also includes the case where other is null
        return false;
    }
    return price <= ((Item)other).getPrice();
}

最佳实践也是在this上添加一个检查,以完全避免强制转换:

public boolean equals(Object other) {
    if (this == other) {
        return true;
    }
    if (!(other instanceof Item)) {
        return false;
    }
    return price <= ((Item)other).getPrice();
}

考虑到这一点,您还应该复习compareTo方法。

最新更新