简体   繁体   English

如何重写equals()方法

[英]How to override equals() method

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 

Then I got another class 然后我再上一堂课

public class CarList
{
        private Collection<Car> cars;

    public CarList()
    {
        cars = new HashSet<>();
    }


   public boolean insertCar(Car car)
    {
        return cars.add(car); 
    }

My question is: How to properly override equals() and hashCode() method, where I consider 'id' and 'name' attribute for object comparsion and hashCode calculation ( so there is no possibility to have 2 objects with the same name and ID - because in this code as it is - it only takes 'id' attribute for object comparsion)? 我的问题是:如何正确覆盖equals()和hashCode()方法,在这里我将'id'和'name'属性用于对象比较和hashCode计算(因此,不可能有两个具有相同名称和ID的对象-因为按原样在此代码中-仅将“ id”属性用于对象比较)?

As of Java 7, there are static methods on Objects that makes implementing hashCode and equals easier. 从Java 7的,也有静态方法Objects ,使得实施hashCodeequals容易。 This should work well, assuming you don't want to use getClass() instead of instanceof to determine type compatibility. 假设您不想使用getClass()而不是instanceof来确定类型兼容性,那么这应该可以很好地工作。 That depends on how subclasses of Car should compare to Car s. 这取决于如何的子类Car应该比较Car秒。

@Override
public boolean equals(Object ob) 
{
    if (!(ob instanceof Car))
    {    
      return false;
    }
 Car that = (Car)ob;
 return Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name);
}

@Override
public int hashCode() 
{
    return Objects.hash(id, name);
}

Instead of using 而不是使用

if (!(ob instanceof Car))
{    
  return false;
}

You should think about using 你应该考虑使用

if (getClass() != obj.getClass())
  return false;

Lets assume you have ForWdCar extends Car and TwoWdCar extends Car with equal name and id. 假设您有具有相同名称和ID的ForWdCar extends CarTwoWdCar extends Car

Do you want them to be equal? 您是否希望他们平等? 1st solution, 第一种解决方案

Do you want them to be unequal? 您是否希望他们不平等? 2nd solution 第二解决方案

You don't care, such cases don't happen? 您不在乎,这样的情况不会发生吗? Second solution, it's faster. 第二种解决方案,它更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM