进阶day03-HashSet存储自定义对象(必定重写hashCode&equasl方法)

This commit is contained in:
2026-02-01 11:57:31 +08:00
parent 2aa143cca1
commit 0426ae9c83
2 changed files with 38 additions and 2 deletions

View File

@@ -0,0 +1,27 @@
package com.inmind.set02;
import java.util.HashSet;
/*
HashSet存储自定义对象
注意我们保存数据时先判断哈希值如果不一样直接存如果哈希值相同还会判断equals方法。
总结:使用HashSet要实现自定义对象的去重,必须重写hashcode和equals,原因底层是哈希表
*/
public class HashSetDemo10 {
public static void main(String[] args) {
//保存几个自定义学生对象,实现去重的效果
HashSet<Student> students = new HashSet<>();
Student s1 = new Student("刘备", 20);
Student s2 = new Student("关羽", 19);
Student s3 = new Student("张飞", 18);
Student s4 = new Student("张飞", 18);
students.add(s1);
students.add(s2);
students.add(s3);
students.add(s4);
System.out.println(students);
}
}

View File

@@ -10,8 +10,8 @@ public class Student {
this.name = name;
this.age = age;
}
//如果没有重写equals方法默认使用==比较地址来判断是否相同
//已经重写了equals方法比较属性的内容
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
@@ -20,10 +20,19 @@ public class Student {
return age == student.age && name.equals(student.name);
}
//当前学生类的哈希值,跟内容有关,属性相同的学生对象的哈希值必定相同
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + age;
return result;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}