java排序
一.背景
java的比较器有两类,分别是Comparable接口和Comparator接口。
二.代码示例
1.Comparator代码
//构造一个排序比较器 Comparator comparator = new Comparator<String>() { @Override public int compare(String o1, String o2) { /*** *该函数返回值r * r > 0, o1排到o2后面 * r < 0, o1排在o2前面 * r ==0 , o1和o2顺序不变 */ if(o1 > o2) return 1; else(o1 < o2) return -1; else return 0; } } //数组排序 String[] str = new String[5]; Arrays.sort(str, comparator); //集合排序 ArrayList<String> list = new ArrayList<String>(); Collections.sort(list, comparator);
2.Comparable代码
class Student implements Comparable<Student>{ private int age; public Student(int age) { this.age = age; } @Override public int compareTo(Student o) { /*** *该函数返回值r * r > 0, 当前对象排到o后面 * r < 0, 当前对象排在o前面 * r ==0 , 当前对象和o顺序不变 */ if(this.age>o.age) return 1; else if(this.age<o.age) return -1; else return 0; } } //数组排序 Student stuArray[]={new Student(20), new Student(22), new Student(20), new Student(26)}; Arrays.sort(stuArray); //数组排序 ArrayList<Student> stuList[]=new ArrayList<Student>(Arrays.asList(new Student(20), new Student(22), new Student(20), new Student(26))); Collections.sort(stuList);