是否有可能比較類,它包含一些其他類的實例,不包含的hashCode和equals與無的hashCode類實例的比較級和等於
我們有3類:Car.java,SUV.java和TestFinal的.java
Car.java(沒有簡單的hashCode POJO和equals)
public class Car
{
private long carId;
private String manufacturer;
public Car(long carId, String manufacturer)
{
super();
this.carId = carId;
this.manufacturer = manufacturer;
}
/**
* @return The carId.
*/
public long getCarId()
{
return carId;
}
/**
* @param carId The carId to set.
*/
public void setCarId(long carId)
{
this.carId = carId;
}
/**
* @return The manufacturer.
*/
public String getManufacturer()
{
return manufacturer;
}
/**
* @param manufacturer The manufacturer to set.
*/
public void setManufacturer(String manufacturer)
{
this.manufacturer = manufacturer;
}
}
SUV.java(含汽車的實例,包含的hashCode和equals)
public class SUV {
private Car car;
/**
* @return The car.
*/
public Car getCar()
{
return car;
}
/**
* @param car The car to set.
*/
public void setCar(Car car)
{
this.car = car;
}
public SUV(Car car)
{
super();
this.car = car;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((car == null) ? 0 : car.hashCode());
return result;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
SUV other = (SUV) obj;
if (car == null)
{
if (other.car != null)
{
return false;
}
}
else if (!car.equals(other.car))
{
return false;
}
return true;
} }
TestFinal是主類,在這裏我比較兩個SUV對象
public class TestFinal
{
public static void main(String args[])
{
Car car1 = new Car(1, "Toyota");
Car car2 = new Car(1, "Toyota");
SUV suv1 = new SUV(car1);
SUV suv2 = new SUV(car2);
System.out.println(suv1.equals(suv2));
}
}
這裏
suv1.equals(SUV2)
返回false,因爲車不包含重寫equals和hashCode。有沒有辦法,我可以更新我的SUV纔是硬道理邏輯無需在汽車的變化(如添加equals和hashCode),使得
suv1.equals(SUV2)
返回true
任何投入或建議將是有價值的。
謝謝!
我想你可以創建包裝類,會覆蓋這些方法,有些在裝飾設計模式爲一體的方式來解決這個問題,但我認爲這將有助於我們理解這個請求背後的動機 - 爲什麼不重寫hashCode和equals,這將是處理這種事情的常用方法? –