在学生类里面重新定义一个方法进行排序
时间: 2023-12-24 15:01:57 浏览: 29
好的,我们可以在学生类中重新定义一个 `compare` 方法来进行排序,示例代码如下:
```java
public class Student {
// 省略其他属性和方法
public static Comparator<Student> sortByAge() {
return new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge() - o2.getAge();
}
};
}
}
```
以上代码中,我们定义了一个静态方法 `sortByAge()`,该方法返回一个比较器对象。这个比较器对象可以用于对学生对象按照年龄进行排序。
接下来,我们可以使用这个比较器对象来创建 TreeSet,并进行排序,示例代码如下:
```java
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<Student> set = new TreeSet<>(Student.sortByAge());
set.add(new Student("001", "张三", 18, "男", "计算机科学与技术", "1班"));
set.add(new Student("002", "李四", 20, "男", "软件工程", "2班"));
set.add(new Student("003", "王五", 19, "女", "信息安全", "3班"));
for (Student student : set) {
System.out.println(student.getName() + " 的年龄是 " + student.getAge());
}
}
}
```
以上代码中,我们在创建 TreeSet 对象时,传入了 `Student.sortByAge()` 方法返回的比较器对象。TreeSet 会根据这个比较器对象对学生对象进行排序。最终,我们遍历 TreeSet 中的元素,输出每个学生的姓名和年龄。