使用Comparable接口
import java.util.TreeSet;
class Student implements Comparable<Student> {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Student other) {
return this.age - other.age;
}
}
public class Main {
public static void main(String[] args) {
TreeSet<Student> studentTreeSet = new TreeSet<>();
studentTreeSet.add(new Student("Alice", 20));
studentTreeSet.add(new Student("Bob", 18));
studentTreeSet.add(new Student("Charlie", 22));
for (Student student : studentTreeSet) {
System.out.println("Name: " + student.getName() + ", Age: " + student.getAge());
}
}
}
使用Comparator接口
import java.util.Comparator;
import java.util.TreeSet;
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
class AgeComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
return s1.getAge() - s2.getAge();
}
}
public class Main {
public static void main(String[] args) {
TreeSet<Student> studentTreeSet = new TreeSet<>(new AgeComparator());
studentTreeSet.add(new Student("Alice", 20));
studentTreeSet.add(new Student("Bob", 18));
studentTreeSet.add(new Student("Charlie", 22));
for (Student student : studentTreeSet) {
System.out.println("Name: " + student.getName() + ", Age: " + student.getAge());
}
}
}