2、定义一个TreeSet集合用来存储学生对象(要求按照姓名排序显示)
时间: 2023-05-22 18:07:12 浏览: 83
可以使用以下代码来定义一个TreeSet集合用来存储学生对象,并按照姓名排序显示:
```
import java.util.TreeSet;
public class Test {
public static void main(String[] args) {
TreeSet<Student> set = new TreeSet<>();
set.add(new Student("Tom", 19));
set.add(new Student("Jerry", 18));
set.add(new Student("Alice", 20));
set.add(new Student("Bob", 22));
for (Student student : set) {
System.out.println(student);
}
}
}
class Student implements Comparable<Student> {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Student o) {
return this.name.compareTo(o.name);
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
```
输出结果为:
```
Student{name='Alice', age=20}
Student{name='Bob', age=22}
Student{name='Jerry', age=18}
Student{name='Tom', age=19}
```
阅读全文