文章目录
一、报错信息
二、解决方案
一、报错信息
使用 Comparator 接口 , 对 ArrayList 集合中的元素排序无效 ;
打印之后没有进行排序 ;
错误代码就不贴出来了 , 随便搜索的代码 , 一用就出错 ;
Java 1.7 1.71.7 及以上的版本中 , Comparator 接口 compare 方法的返回值必须是一对相反的数值 , 如 − 1 -1−1 和 + 1 +1+1 ; 不能返回 1 11 和 0 00 ;
二、解决方案
Comparator 接口 正确的使用方法 :
list.sort(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { // 升序排序 if (o1.age > o2.age) { return 1; } else { return -1; } } });
完整代码示例 :
import java.util.ArrayList; import java.util.Comparator; public class Sort { static class Student{ String name; int age; public Student(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } } public static void main(String[] args) { // 构造对象 ArrayList<Student> list = new ArrayList<>(); list.add(new Student("Tom", 18)); list.add(new Student("Jerry", 14)); list.add(new Student("Cat", 20)); list.add(new Student("Mouse", 19)); list.sort(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { // 升序排序 if (o1.age > o2.age) { return 1; } else { return -1; } } }); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i).toString()); } } }
执行结果 :