进阶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

@@ -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 +
'}';
}
}