1.创建学生类
package bean;
import java.util.Objects;
public class Student {
// 属性
private String name;
// 构造方法
public Student() {
}
public Student(String name) {
this.name = name;
}
// getter and setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
2.测试数据
package collection;
import bean.Student;
import java.util.HashSet;
import java.util.Set;
public class HashMapTest02 {
public static void main(String[] args) {
bean.Student s1 = new Student("zhangsan");
bean.Student s2 = new Student("zhangsan");
// 重写equals方法之前是false
//System.out.println(s1.equals(s2)); // false
// 重写equals方法之后是true
System.out.println(s1.equals(s2)); // true
System.out.println("s1的hashCode=" + s1.hashCode());
System.out.println("s1的hashCode=" + s2.hashCode());
Set<bean.Student> students = new HashSet<>();
students.add(s1);
students.add(s2);
System.out.println(students.size()); // hashCode方法重写前是2,重写后是1
}
}
|