java使用TreeSet集合,对其添加4个教师对象,教师对象有姓名和年龄、职称属性,要求按照教师的姓名将教师信息升序输出。
时间: 2024-01-14 09:04:15 浏览: 66
Java TreeSet实现学生按年龄大小和姓名排序的方法示例
5星 · 资源好评率100%
可以按照以下步骤实现:
1. 创建教师类,包括姓名、年龄和职称属性。
```java
public class Teacher implements Comparable<Teacher> {
private String name;
private int age;
private String title;
public Teacher(String name, int age, String title) {
this.name = name;
this.age = age;
this.title = title;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getTitle() {
return title;
}
@Override
public int compareTo(Teacher o) {
return this.name.compareTo(o.getName());
}
}
```
2. 创建TreeSet集合,并添加教师对象。
```java
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<Teacher> teacherSet = new TreeSet<>();
Teacher teacher1 = new Teacher("Tom", 35, "Associate Professor");
Teacher teacher2 = new Teacher("Jerry", 28, "Lecturer");
Teacher teacher3 = new Teacher("Alice", 40, "Professor");
Teacher teacher4 = new Teacher("Bob", 30, "Assistant Professor");
teacherSet.add(teacher1);
teacherSet.add(teacher2);
teacherSet.add(teacher3);
teacherSet.add(teacher4);
for (Teacher teacher : teacherSet) {
System.out.println(teacher.getName() + ", " + teacher.getAge() + ", " + teacher.getTitle());
}
}
}
```
3. 运行程序,输出结果。
```
Alice, 40, Professor
Bob, 30, Assistant Professor
Jerry, 28, Lecturer
Tom, 35, Associate Professor
```
可以看到,教师信息按照姓名升序输出。
阅读全文