使用TreeSet存储教室对象,教室对象包括教室号no,教室地址 address,教室容纳人数 count,使用教室号排序。遍历TreeSet.
时间: 2024-02-27 17:53:13 浏览: 55
首先,我们需要定义一个教室类,包括教室号no、教室地址address和教室容纳人数count。教室类需要实现Comparable接口,并重写compareTo方法,以实现按照教室号排序。
代码如下:
```java
import java.util.TreeSet;
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.getNo());
}
public static void main(String[] args) {
// 创建TreeSet对象
TreeSet<Classroom> set = new TreeSet<>();
// 添加教室对象
set.add(new Classroom("101", "A栋", 50));
set.add(new Classroom("104", "A栋", 100));
set.add(new Classroom("102", "B栋", 80));
set.add(new Classroom("103", "C栋", 60));
// 遍历TreeSet
for (Classroom classroom : set) {
System.out.println(classroom.getNo() + " " + classroom.getAddress() + " " + classroom.getCount());
}
}
}
```
输出结果为:
```
101 A栋 50
102 B栋 80
103 C栋 60
104 A栋 100
```
可以看到,教室对象按照教室号从小到大排序。遍历TreeSet时,可以直接使用foreach循环。
阅读全文