定义一个TreeSet集合用来存储学生对象
时间: 2023-05-22 21:07:11 浏览: 55
Java TreeSet实现学生按年龄大小和姓名排序的方法示例
5星 · 资源好评率100%
好的,可以通过以下代码定义一个TreeSet集合用来存储学生对象:
```java
import java.util.TreeSet;
public 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 student) {
if (this.age > student.getAge()) {
return 1;
} else if (this.age < student.getAge()) {
return -1;
} else {
return this.name.compareTo(student.getName());
}
}
public static void main(String[] args) {
TreeSet<Student> set = new TreeSet<>();
set.add(new Student("Tom", 20));
set.add(new Student("Kate", 18));
set.add(new Student("Jack", 22));
for (Student s : set) {
System.out.println("name: " + s.getName() + " age: " + s.getAge());
}
}
}
```
这段代码实现了Comparable接口,根据学生对象的年龄和姓名进行升序排序,输出结果为:
```
name: Kate age: 18
name: Tom age: 20
name: Jack age: 22
```
阅读全文