Java:使用TreeSet存储教室对象,教室对象包括教室号no,教室地址 address,教室容纳人数 count,使用教室号排序。遍历TreeSet.
时间: 2024-02-15 16:02:10 浏览: 60
学生成绩排序(TreeSet方式实现)
可以按照以下步骤实现:
1. 创建一个教室类,包括教室号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 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());
}
}
```
2. 创建一个TreeSet对象,并将教室对象添加进去。
```java
TreeSet<Classroom> classrooms = new TreeSet<>();
classrooms.add(new Classroom("A101", "教学楼A101", 80));
classrooms.add(new Classroom("B201", "教学楼B201", 120));
classrooms.add(new Classroom("C301", "教学楼C301", 50));
```
3. 遍历TreeSet,输出教室信息。
```java
for (Classroom classroom : classrooms) {
System.out.println("教室号:" + classroom.getNo() + ",教室地址:" + classroom.getAddress() + ",教室容纳人数:" + classroom.getCount());
}
```
阅读全文