学生类 - 属性:姓名、地址、年龄 测试类: - 使用TreeMap集合保存学生对象信息,要求创建不低于五个学生对象 - 集合添加元素时,要求以学生对象为键,住址为值 - TreeMap集合按照学生的年龄从大到小排序后,遍历集合并输出键值内容,输出格式不做要求
时间: 2024-05-01 07:20:02 浏览: 163
以下是Java代码实现:
```java
import java.util.Map;
import java.util.TreeMap;
public class TestStudent {
public static void main(String[] args) {
Map<Student, String> map = new TreeMap<>((s1, s2) -> s2.getAge() - s1.getAge()); // 按照年龄从大到小排序
map.put(new Student("Tom", "Beijing", 18), "Address1");
map.put(new Student("Jerry", "Shanghai", 20), "Address2");
map.put(new Student("Alice", "Guangzhou", 22), "Address3");
map.put(new Student("Bob", "Shenzhen", 19), "Address4");
map.put(new Student("Lucy", "Hangzhou", 21), "Address5");
for (Map.Entry<Student, String> entry : map.entrySet()) {
System.out.println(entry.getKey().toString() + " Address:" + entry.getValue());
}
}
}
class Student {
private String name;
private String address;
private int age;
public Student(String name, String address, int age) {
this.name = name;
this.address = address;
this.age = age;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
", age=" + age +
'}';
}
}
```
输出结果为:
```
Student{name='Alice', address='Guangzhou', age=22} Address:Address3
Student{name='Lucy', address='Hangzhou', age=21} Address:Address5
Student{name='Jerry', address='Shanghai', age=20} Address:Address2
Student{name='Bob', address='Shenzhen', age=19} Address:Address4
Student{name='Tom', address='Beijing', age=18} Address:Address1
```
阅读全文