使用TreeSet存储教室对象,教室对象包括教室号no,教室地址 address,教室容纳人数 count,使用教室号排序。遍历TreeSet.
时间: 2024-02-03 18:14:07 浏览: 44
用文件存储10个学生的姓名、学号、手机号、地址,可通过姓名或者学号查找
5星 · 资源好评率100%
首先,我们需要创建一个教室类,包含教室号、教室地址和教室容纳人数三个属性,并实现 `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 void setNo(String no) {
this.no = no;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public int compareTo(Classroom o) {
return this.no.compareTo(o.no);
}
}
```
接下来,我们创建一个 `TreeSet` 对象,并添加若干教室对象。由于 `TreeSet` 会自动按照元素的自然顺序进行排序,因此我们不需要手动进行排序操作。
```java
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<Classroom> classrooms = new TreeSet<>();
classrooms.add(new Classroom("101", "教学楼A101", 50));
classrooms.add(new Classroom("102", "教学楼A102", 80));
classrooms.add(new Classroom("103", "教学楼A103", 100));
for (Classroom classroom : classrooms) {
System.out.println(classroom.getNo() + " " + classroom.getAddress() + " " + classroom.getCount());
}
}
}
```
最后,我们遍历 `TreeSet`,输出每个教室对象的信息。输出结果如下:
```
101 教学楼A101 50
102 教学楼A102 80
103 教学楼A103 100
```
阅读全文