public class Car
{
private String name;
public int id;
public Car(String name, int id)
{
this.name = name;
this.id = id;
}
@Override
public boolean equals(Object ob)
{
if (!(ob instanceof Car))
{
return false;
}
Car that = (Car)ob;
return this.id == that.id;
}
@Override
public int hashCode()
{
return id;
}
// this class also got getters and setters
然后我又上了一节课
public class CarList
{
private Collection<Car> cars;
public CarList()
{
cars = new HashSet<>();
}
public boolean insertCar(Car car)
{
return cars.add(car);
}
我的问题是:如何正确覆盖 equals() 和 hashCode() 方法,我考虑对象比较和 hashCode 计算的 'id' 和 'name' 属性(因此不可能有 2 个具有相同名称和 ID 的对象- 因为在这段代码中 - 它只需要'id'属性来进行对象比较)?