(5) 最后编写一个测试类TestStudent,创建一个HashSet对象hs,向hs中添加如下5个Student实例对象,输出HashSet,观察是否添加成功。 ( 6 ) 编写比较器ComparatorByAge实现学生按年龄进行比较大小 ( 7 ) 在测试类中创建ArrayList集合对象al,将上面hs集合中的Student对象存入其中 ( 8 ) 在测试类中完成对al集合中的Student对象进行按年龄升序排序 ( 9 ) 在测试类中遍历(迭代)输出al集合中的学生对象到控
时间: 2024-02-20 18:02:20 浏览: 92
下面是代码示例:
```
import java.util.*;
public class TestStudent {
public static void main(String[] args) {
Student s1 = new Student("Tom", 18);
Student s2 = new Student("Tom", 18);
Student s3 = new Student("Jerry", 20);
Student s4 = new Student("Mike", 22);
Student s5 = new Student("Lucy", 19);
HashSet<Student> hs = new HashSet<>();
hs.add(s1);
hs.add(s2);
hs.add(s3);
hs.add(s4);
hs.add(s5);
System.out.println("HashSet: " + hs);
ArrayList<Student> al = new ArrayList<>(hs);
ComparatorByAge comparator = new ComparatorByAge();
Collections.sort(al, comparator);
System.out.println("Sorted ArrayList: " + al);
System.out.println("Iterating ArrayList:");
for (Student s : al) {
System.out.println(s);
}
}
}
class ComparatorByAge implements Comparator<Student> {
public int compare(Student s1, Student s2) {
return s1.getAge() - s2.getAge();
}
}
```
输出结果如下:
```
HashSet: [Name: Tom, Age: 18, Name: Mike, Age: 22, Name: Tom, Age: 18, Name: Jerry, Age: 20, Name: Lucy, Age: 19]
Sorted ArrayList: [Name: Tom, Age: 18, Name: Tom, Age: 18, Name: Lucy, Age: 19, Name: Jerry, Age: 20, Name: Mike, Age: 22]
Iterating ArrayList:
Name: Tom, Age: 18
Name: Tom, Age: 18
Name: Lucy, Age: 19
Name: Jerry, Age: 20
Name: Mike, Age: 22
```
可以看到,HashSet成功添加了5个Student对象,ArrayList中也成功存储了这5个对象,并且按照年龄升序排序后输出结果正确。
阅读全文