/* Collections中还有一个sort方法,可以根据比较器排序 static void sort(List list, Comparator c): 参数list:是要排序的集合 参数c: 是比较器, 好比一个法官。 如果使用比较器排序,那么这个集合的泛型是不需要实现Comparable接口的。 总结: 一个类实现Comparable接口,表示这个类的对象本身就具备了排序的功能,这种排序叫做自己排序。 另一种方式是比较器排序,如果对象本身并不具备自然排序的功能,那么可以找一个法官帮这些对象 进行排序,这个法官就是比较器。 重点掌握比较器。 */
public class Demo03Collections { public static void main(String[] args) { ArrayList<Student> hs=new ArrayList<>();/使用比较器进行排序,泛型Student此时不需要实现Compareable接口; Collections.addAll(hs,new Student("大幂幂",19), new Student("金星",22),new Student("凤姐",99)); // static void sort(List list, Comparator c): Collections.sort(hs,new Rule());//创建rule类实现comparator接口 System.out.println(hs); } } //创建rule类实现了比较器的接口,rule里重写了比较规则。
public class Rule implements Comparator<Student> { /* 如果返回值是0,表示o1和o1相等 如果返回值是负数,表示o1比o2小 如果返回值是整数,表示o1比o2大 升序就是1减2 降序就是2减1 */ @Override public int compare(Student o1, Student o2) { return o2.getAge()-o1.getAge(); } }