gpt4 book ai didi

java - 无法在基元上调用 Equals 方法->重写 Equals 方法不起作用 - Java 中初学者的错误

转载 作者:行者123 更新时间:2023-12-02 01:36:13 25 4
gpt4 key购买 nike

我在重写 Equals 方法时遇到编译错误,更具体地说是在 Float 和双括号、重量和价格属性中,HashCode 方法似乎有效,所以我不知道问题出在我的代码中。该代码还包含一个车辆接口(interface),但我不认为错误来自该接口(interface)。我不确定我是否完全理解了 Equals 方法。有人可以帮助我吗?

 package info.vehicle;

import java.io.Serializable;

public class Car implements Vehicle,Serializable,Cloneable {
private float weight;
private double price;
private String producer;


public Car()
{

}

public Car(float _weight,double _price,String _producer)
{
weight=_weight;
price=_price;
producer=_producer;
}

public void setProducer(String _producer) throws Exception
{
if(_producer!=null && _producer.length()>1)
this.producer=_producer;

else
{
throw new Exception("Producer must not be null.");
}
}

public void setPrice(double _price) throws Exception
{
if(_price>0)
{
price=_price;
}
else
{
throw new Exception("Price must not be 0.");
}
}

public void setWeight(float _weight) throws Exception
{
if(weight>0)
{
weight=_weight;
}
else
{
throw new Exception("Weight must be different than 0.");
}

}

@Override
public boolean equals(Object obj) {
Car other=(Car)obj;
if(((Float)(this.weight)).equals(Float)other.weight)
{

if((Double)(this.price)).equals((Double)other.price))
{
if(this.producer.contentEquals(other.producer))
{
return super.equals(obj);
}
}
}

return false;
}

@Override
protected Object clone() throws CloneNotSupportedException {
Car temp=new Car();
temp.weight=this.weight;
temp.price=this.price;
temp.producer=this.producer;
return temp;
}

@Override
public int hashCode() {
final int prime=31;
int result=0;
result+=(int)weight*prime;
result+=(int)price*prime;
result+=producer.length()*prime;
return result;
}






@Override
public String infoVehicle() {

return producer;
}

}

最佳答案

简单的语法错误。

equals(Float)other.weight)

应该是

equals((Float) other.weight)

if((Double)(this.price))

应该是

if(((Double)(this.price))

但是你为什么要明确地转换它们?

关于java - 无法在基元上调用 Equals 方法->重写 Equals 方法不起作用 - Java 中初学者的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55227244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com