使用treeset存储教室对象,教室对象包括教室号弄,教室地址address,教室容纳人数count,使用教室号排序,遍历treeset
时间: 2024-01-06 12:06:30 浏览: 97
好的,我可以给你一个示例代码:
首先,我们需要定义一个教室类:
```java
public class Classroom implements Comparable<Classroom> {
private String roomNumber;
private String address;
private int capacity;
public Classroom(String roomNumber, String address, int capacity) {
this.roomNumber = roomNumber;
this.address = address;
this.capacity = capacity;
}
public String getRoomNumber() {
return roomNumber;
}
public String getAddress() {
return address;
}
public int getCapacity() {
return capacity;
}
@Override
public int compareTo(Classroom o) {
return this.roomNumber.compareTo(o.getRoomNumber());
}
}
```
这里实现了 `Comparable` 接口,以便使用 `TreeSet` 进行排序。按照教室号进行升序排序。
然后,我们可以创建一个 `TreeSet` 对象,并添加一些教室对象:
```java
public static void main(String[] args) {
Set<Classroom> classroomSet = new TreeSet<>();
Classroom c1 = new Classroom("101", "A Building", 50);
Classroom c2 = new Classroom("102", "A Building", 60);
Classroom c3 = new Classroom("103", "B Building", 70);
classroomSet.add(c1);
classroomSet.add(c2);
classroomSet.add(c3);
for (Classroom classroom : classroomSet) {
System.out.println(classroom.getRoomNumber() + " " + classroom.getAddress() + " " + classroom.getCapacity());
}
}
```
这里,我们创建了三个教室对象,并将它们添加到 `TreeSet` 中。最后,我们使用 `for-each` 循环遍历 `TreeSet` 中的元素,并按照教室号进行排序输出。
输出结果为:
```
101 A Building 50
102 A Building 60
103 B Building 70
```
希望这个示例能够帮到你!
阅读全文