不使用Collections工具类,如何按score属性对Student数组排序?
按Student的score属性排序数组的修复方案
常见错误及修复步骤
未导入必要类
你的sortByScore类实现了Comparator<Student>,但代码里没导入对应的包,需在代码顶部添加:import java.util.Comparator;另外排序数组要用
Arrays.sort方法,也要导入:import java.util.Arrays;Student的score属性访问权限问题
如果Student类中score是private修饰的,直接访问a.score会触发编译错误。给Student类添加获取score的方法:class Student { private int score; // 构造方法、其他属性 public int getScore() { return score; } }然后修改Comparator的compare方法:
class sortByScore implements Comparator<Student> { @Override public int compare(Student a, Student b) { return a.getScore() - b.getScore(); } }正确调用数组排序方法
对Student数组排序时,要使用带Comparator参数的Arrays.sort重载方法:// 假设你的Student数组是students Student[] students = new Student[]{/* 初始化数组元素 */}; Arrays.sort(students, new sortByScore());
简化写法(可选)
如果不想单独写sortByScore类,用匿名内部类可以一步完成:
Arrays.sort(students, new Comparator<Student>() { @Override public int compare(Student a, Student b) { return a.getScore() - b.getScore(); } });
内容的提问来源于stack exchange,提问作者amin ettefaghi
相关产品推荐
相关产品推荐

