一个小案例来理解实体类中重写equals()和hashCode()方法的必要性

一世执手 提交于 2019-12-06 02:09:09

今天在使用list的indexOf()方法时,自己新添加的一个对象,通过list的indexOf来查看list里面有没有这个对象,但是无论怎么尝试都返回-1(无法获取到指定的对象),后来发现是实体类对象没有重写equals()和hashCode()方法。代码的案例如下:

1.实体类emp如下:

public class Employee{
    private int id;
    private int name;
    
    //构造方法
    public Employee(String name){
          this.name =name;
    }

    //省略get,set方法...
}        

 

2.写一个测试方法,我们希望手动添加一个Emp对象,通过list的indexOf方法来找到已有的emp对象name相同的emp对象。

    public static void main(String[] args) {

        Employee emp1 = new Employee();//创建第一个员工
        emp1.setName("test1");

        Employee emp2 = new Employee();//创建第二个员工
        emp2.setName("test2");

        List<Employee> emps = new ArrayList<>();//将员工存入到list
        emps.add(emp1);
        emps.add(emp2);

        int index = emps.indexOf(new Employee("test1"));//手动添加一个emp对象
        System.out.println(index);
    }

以上结果,按道理讲我们新添加的 new Employee("test1")  该对象应该是在list里面有的,但是运行后发现,结果却是返回了index=-1,这是因为我们没有在实体类Employee中,将name属性添加hashCode和equals方法

 

3.将实体类中添加hashCode() 和 equals()后,重新运行结果:

  (1)修改实体类Employee,为其name属性添加equals和hashCode方法:

  

public class Employee{
    private int id;
    private int name;
    
    //构造方法
    public Employee(String name){
          this.name =name;
    }
    //添加hashCode和equals方法
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return name.equals(employee.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }
    //省略get,set方法...
} 

  (2)这个时候我们查找指定的name属性的类,重新运行后发现,index返回了我们需要查找的name的employee对象的索引位置:

 

 

吾生也有涯 而知也无涯!

   

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!