关于Comparator的问题
来源:3-5 编程练习
慕沐9390268
2020-06-19 10:50:35
老师你好,
请问重写的compare一定要再封装到一个StudentComparator类中吗?不可以直接写在StudentTest类中吗?如下图所示:

2回答
wangstudyvc
2020-06-22
import java.util.Comparator;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
//实现Comparator接口
public class StudentTest {
public static void main(String[] args){
// 定义Student类的对象
Student stu1 = new Student(40, "peter", 20);
Student stu2 = new Student(28, "angel", 5);
Student stu3 = new Student(35, "tom", 18);
// 将对象添加到List中
List<Student> stuList = new ArrayList<Student>(3);
stuList.add(stu1);
stuList.add(stu2);
stuList.add(stu3);
// 输出排序前的数据
System.out.println("按名字排序前:");
for(Student stu:stuList) {
System.out.println(stu);
}
// 排序
Collections.sort(stuList, new StudentComparator());
// 输出排序后的数据
System.out.println("按名字排序后:");
for(Student stu:stuList) {
System.out.println(stu);
}
}
}
class StudentComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o1.getName().compareTo(o2.getName());
}
}还是这么写比较合理,最好是单独写一个比较器的类,以后复用方便。这里不具备这个条件,就在同一个文件中写一个类,也是相当而言,更加单一职责吧
好帮手慕小尤
2020-06-19
同学你好,同学描述的是否是Comparator接口。如果是,则是可以直接写在StudentTest类中的。不是一定要封装到StudentComparator类中的。如同学反馈的代码所示:
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
相似问题
回答 1