创建一个TreeSet集合,在集合中放入3个学生对象(其中一个学生的信息是你自己的信息),在集合中以年龄顺序排序,遍历集合并把学生对象信息打印在控制台上。学生类具有姓名,年龄属性。
时间: 2024-03-03 13:47:50 浏览: 28
好的,以下是Java代码实现:
```java
import java.util.TreeSet;
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Student o) {
return Integer.compare(this.age, o.age);
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
public static void main(String[] args) {
TreeSet<Student> set = new TreeSet<>();
set.add(new Student("Tom", 22));
set.add(new Student("Jerry", 25));
set.add(new Student("Lucy", 20));
set.add(new Student("你的名字", 18)); // 自己的信息
for (Student student : set) {
System.out.println(student);
}
}
}
```
你可以将上述代码复制到Java IDE中进行编译运行,程序会创建一个TreeSet集合,向其中添加3个学生对象(其中一个学生的信息是你自己的信息),然后根据学生对象的年龄属性进行排序,并遍历集合打印每个学生对象的信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)