使用java编写程序,使用TreeSet存储教室对象,教室对象包括教室号no,教室地址 address,教室容纳人数 count,使用教室号排序。遍历TreeSet.
时间: 2024-02-16 18:02:56 浏览: 53
以下是使用Java编写程序,使用TreeSet存储教室对象,遍历TreeSet并按照教室号排序的示例代码:
```java
import java.util.*;
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 this.no.compareTo(o.getNo());
}
public static void main(String[] args) {
Set<Classroom> classrooms = new TreeSet<>();
classrooms.add(new Classroom("A101", "Main Building", 50));
classrooms.add(new Classroom("A102", "Main Building", 60));
classrooms.add(new Classroom("B101", "Science Building", 70));
classrooms.add(new Classroom("C201", "Engineering Building", 80));
for (Classroom classroom : classrooms) {
System.out.println(classroom.getNo() + " " + classroom.getAddress() + " " + classroom.getCount());
}
}
}
```
在这个示例中,我们定义了一个`Classroom`类,实现了`Comparable`接口以便可以按照教室号进行排序。我们创建了一个`TreeSet`对象来存储`Classroom`对象,并添加了一些示例数据。最后,我们使用for-each循环遍历`TreeSet`并输出每个对象的教室号、地址和容纳人数。由于`TreeSet`会自动按照教室号进行排序,因此我们可以保证输出的顺序是按照教室号排序的。
阅读全文