重写equals方法以接受对象类内部的双精度。JAVA
在equals方法中比较double时,我似乎遇到了一个问题。我收到一个错误,说重写equals方法以接受对象类内部的双精度。JAVA,java,object,boolean,double,Java,Object,Boolean,Double,在equals方法中比较double时,我似乎遇到了一个问题。我收到一个错误,说java.lang.ClassCastException:和java.lang.Double不能转换为项。我的施法不正确吗?当我将强制转换更改为Double时,我收到错误找不到符号-方法getPrice()。 公共类项实现可比较 { 私有字符串名称、类别; 私人整数数量; 私人双价; 公共项目(字符串nam、字符串cate、整数、双优先级) { 姓名=不结盟运动; 类别=美食; 数量=数量; 价格=pric; } 公
java.lang.ClassCastException:和java.lang.Double
不能转换为项。我的施法不正确吗?当我将强制转换更改为Double时,我收到错误找不到符号-方法getPrice()。
公共类项实现可比较
{
私有字符串名称、类别;
私人整数数量;
私人双价;
公共项目(字符串nam、字符串cate、整数、双优先级)
{
姓名=不结盟运动;
类别=美食;
数量=数量;
价格=pric;
}
公共字符串toString()
{
返回名称+”,“+类别+”,“+数量+”,“+价格;
}
公共布尔等于(对象其他)
{
如果(价格其他价格?+1:价格<其他价格?-1:0;
返回结果;
}
}
我假设传递到compareTo方法中的其他方法是一个项
所以你有一个其他的项目,和一个双倍的其他价格
然后,当您在if语句中调用this.equals(otherPrice)
时,您正在执行项.equals(Double)
你应该传入一个项目。我想你应该用ObjectotherPrice=((项目)其他);
替换double-otherPrice=((项目)其他);
查看是否将一个double传递给equals方法,并将该double强制转换为一个项,这是不正确的。请注意,Java中的方法将对象作为参数。对于该方法也是如此。这意味着该参数可以是任何类型(字符串、列表、double…),我怀疑这就是这里发生的情况
在equals
方法中,您将参数其他
强制转换为项
。但是如果其他
不是项
,该怎么办
在与操作员进行铸造之前,应检查其他的类型,如下所示:
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();
}
记住这一点,您还应该检查您的compareTo
方法。您的问题在于您的compareTo方法。您正在尝试将您的Item对象与double进行比较。
您的方法应如下所示:
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;
}
public int compareTo(对象其他){
int结果;
double otherPrice=((项目)other).getPrice();
字符串otherCategory=((项)other).getCategory();
if(this.price==其他价格)
结果=类别。与(其他类别)比较;
其他的
结果=价格>其他价格?+1:价格<其他价格?-1:0;
返回结果;
}
Item.equals将传递的对象强制转换为Item,但您使用Double调用它,它不能强制转换为除Number和Object之外的任何对象。有关如何正确实现equals和相关问题,请参阅。@AngularLover,这不会有帮助…Java Autobox。为什么这个问题会被问两次?我喜欢这个建议,非常正确。我认为真实的是这里的sue是,他将一个double传递给equals方法,然后将其投射到一个项目。
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof Item)) {
return false;
}
return price <= ((Item)other).getPrice();
}
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;
}