s-day04-TreeSet保存自定义对象

This commit is contained in:
2026-08-03 11:21:20 +08:00
parent a8e41fe203
commit 143e8e0f59
2 changed files with 72 additions and 0 deletions
@@ -0,0 +1,41 @@
package com.inmind.treeset02;
import java.util.Objects;
public class Student implements Comparable<Student>{
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
int result = Objects.hashCode(name);
result = 31 * result + age;
return result;
}
@Override
public int compareTo(Student o) {
return this.age - o.age;
}
}