使用TreeSet存储教室对象,教室对象包括教室号no,教室地址 address,教室容纳人数 count,使用教室号排序。遍历TreeSet.
时间: 2024-02-03 18:15:34 浏览: 65
用文件存储10个学生的姓名、学号、手机号、地址,可通过姓名或者学号查找
5星 · 资源好评率100%
首先,我们需要创建一个教室类 Classroom,包含教室号no、教室地址address和教室容纳人数count,并实现 Comparable 接口以便使用教室号进行排序。
```java
public class Classroom implements Comparable<Classroom>{
private String no;
private String address;
private int count;
public Classroom(String no, String address, int count) {
this.no = no;
this.address = address;
this.count = count;
}
public String getNo() {
return no;
}
public String getAddress() {
return address;
}
public int getCount() {
return count;
}
@Override
public int compareTo(Classroom o) {
return no.compareTo(o.getNo());
}
}
```
然后,我们可以创建一个 TreeSet 对象,并将多个 Classroom 对象添加到其中:
```java
TreeSet<Classroom> classrooms = new TreeSet<>();
classrooms.add(new Classroom("C101", "教学楼1", 50));
classrooms.add(new Classroom("C102", "教学楼1", 60));
classrooms.add(new Classroom("C103", "教学楼2", 70));
classrooms.add(new Classroom("C104", "教学楼2", 80));
```
最后,我们可以使用 for-each 循环遍历 TreeSet,输出每个教室的信息:
```java
for (Classroom classroom : classrooms) {
System.out.println(classroom.getNo() + " " + classroom.getAddress() + " " + classroom.getCount());
}
```
输出结果如下:
```
C101 教学楼1 50
C102 教学楼1 60
C103 教学楼2 70
C104 教学楼2 80
```
阅读全文