使用Java编写程序实现(1)定义School类包含两个属性:学校名称name(String),在校人数num(int))(2)实现Comparable接口,按照学校人数排序。(3)采用TreeSet容器存储School类的三个对象。(4)使用Iterator,遍历输出容器中各School对象的学生人数)
时间: 2024-01-20 12:04:19 浏览: 56
创建学生类Student,继承自SchoolPerson类, 添加额外两个属性:班级class、学号sno。 添加方法:打印学生的所有信息print_info方法。
5星 · 资源好评率100%
好的,下面是实现代码:
```java
import java.util.Iterator;
import java.util.TreeSet;
public class School implements Comparable<School> {
private String name;
private int num;
public School(String name, int num) {
this.name = name;
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
@Override
public int compareTo(School o) {
return this.num - o.num;
}
public static void main(String[] args) {
School s1 = new School("School A", 1000);
School s2 = new School("School B", 2000);
School s3 = new School("School C", 1500);
TreeSet<School> set = new TreeSet<>();
set.add(s1);
set.add(s2);
set.add(s3);
Iterator<School> iterator = set.iterator();
while (iterator.hasNext()) {
School school = iterator.next();
System.out.println(school.getNum());
}
}
}
```
上面的代码中,我们实现了Comparable接口,并实现了compareTo方法,按照学校人数进行排序。然后使用TreeSet容器存储三个School对象,并使用Iterator遍历输出每个School对象的学生人数。
阅读全文