定义一个学生类,有学号number,姓名name,年龄age,性别sax,院系yuanXi,班级classes,再定义一个学生类帮我用TreeSet将年龄进行排序
时间: 2023-08-13 18:06:28 浏览: 93
好的,以下是定义学生类的示例代码:
```java
public class Student implements Comparable<Student> {
private String number;
private String name;
private int age;
private String sex;
private String yuanXi;
private String classes;
public Student(String number, String name, int age, String sex, String yuanXi, String classes) {
this.number = number;
this.name = name;
this.age = age;
this.sex = sex;
this.yuanXi = yuanXi;
this.classes = classes;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getYuanXi() {
return yuanXi;
}
public void setYuanXi(String yuanXi) {
this.yuanXi = yuanXi;
}
public String getClasses() {
return classes;
}
public void setClasses(String classes) {
this.classes = classes;
}
@Override
public int compareTo(Student o) {
return this.age - o.getAge();
}
}
```
接下来,我们可以使用 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, "男", "计算机科学与技术", "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 对象,并向其中添加了三个学生对象,TreeSet 会自动按照学生的年龄进行排序。最终,我们遍历 TreeSet 中的元素,输出每个学生的姓名和年龄。
阅读全文