有七个学生,他们有学号,姓名,性别,年龄,院系,班级定义一个方法,按照年龄用TreeSet排序
时间: 2023-07-27 12:11:30 浏览: 82
解决TreeSet类的排序问题
5星 · 资源好评率100%
可以先定义一个学生类,包含学号、姓名、性别、年龄、院系、班级等属性,并实现 `Comparable` 接口来实现按照年龄排序。代码如下:
```java
public class Student implements Comparable<Student> {
private String id;
private String name;
private String gender;
private int age;
private String department;
private String clazz;
public Student(String id, String name, String gender, int age, String department, String clazz) {
this.id = id;
this.name = name;
this.gender = gender;
this.age = age;
this.department = department;
this.clazz = clazz;
}
// 实现 compareTo 方法,按照年龄进行比较
@Override
public int compareTo(Student o) {
return Integer.compare(this.age, o.age);
}
// 省略 getter 和 setter 方法
}
```
然后在主函数中创建七个学生对象,放入 `TreeSet` 中进行排序,代码如下:
```java
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<Student> set = new TreeSet<>();
set.add(new Student("001", "张三", "男", 18, "计算机科学与技术", "计科1901"));
set.add(new Student("002", "李四", "女", 19, "软件工程", "软工1902"));
set.add(new Student("003", "王五", "男", 20, "信息安全", "信安1903"));
set.add(new Student("004", "赵六", "女", 21, "网络工程", "网工1901"));
set.add(new Student("005", "钱七", "男", 22, "物联网", "物联网1902"));
set.add(new Student("006", "孙八", "女", 23, "人工智能", "AI1903"));
set.add(new Student("007", "周九", "男", 24, "数据科学与大数据技术", "数据1901"));
for (Student student : set) {
System.out.println(student.getName() + " " + student.getAge());
}
}
}
```
输出结果如下:
```
张三 18
李四 19
王五 20
赵六 21
钱七 22
孙八 23
周九 24
```
阅读全文