一般来说我们重写equals()方法会用的比较多,我们在比较两个自定义类型的变量的时候,比如有这样一个自定义的类型Student:9)
package com.springstudy.testimport.pojo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import java.util.Objects;
@Component
public class Student implements Cloneable{
@Override
public Object clone() throws CloneNotSupportedException {
return (Student)super.clone();
}
private String name;
private Integer age;
public Student(String name,Integer age){
this.name=name;
this.age=age;
}
public Student(){}
public String getName() {
return name;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
@Bean
@Scope(value = WebApplicationContext.SCOPE_SESSION,proxyMode = ScopedProxyMode.TARGET_CLASS)
public Student cacheStudent(){
return new Student();
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return name.equals(student.name) && age.equals(student.age);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
在比较两个Student对象的时候,如果直接用==符号判断,那肯定是不相等的,(因为我们知道这两个引用变量指向的是两个不同的new出来的对象)但我们一般不希望两个Student这样比较是否相等,我们一般希望比较两个对象的具体信息.所以因为有这个需求,所以重写了equals方法.然后判相等的时候使用.equals()来判断.
那为什么一定要再去重写一下hashcode()方法呢?
因为为了满足Set集合存储元素原则的需要.因为我们希望Set集合在存储Student对象的时候也是通过像equals()方法那样去去重.
版权声明:本文为qq_34116044原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。