基本概念java中,对数组对象和集合对象排序,有两种实现方法
即: (1)对象实现Comparable接口。
(2)定义比较器,实现Comparator接口。
一、Comparable接口:
1、此接口对每个实现它的类的对象施加了一个总排序,这个排序成为类的自然排序,这个类的CompareTo方法被称为自然比较方法。
2、若一个类实现了Comparable接口,就意味着该类支持排序。实现了该接口的类的数组对象或集合对就可以使用Arrays.sort或Collections.sort方法进行排序。
/*** 实体类*/public class Person implements Comparable<Person>{String name;int age;// 方式一@Overridepublic int compareTo(Student o) {if (this.age>o.age)return 1;else if (this.age<o.age)return -1;return 0;}// 方式二@Overridepublic int compareTo(Student o) {return this.age - o.age;}}public class ComparableTest {public static void main(String[] args) {Student[] stu=new Student[]{new Student("魏宇明",18),new Student("蔡林虎",21),new Student("袁新槐",19)};System.out.println("对象数组排序前:"+Arrays.toString(stu));Arrays.sort(stu);System.out.println("对象数组排序后:"+Arrays.toString(stu));List<Student> list=new ArrayList<>();list.add(new Student("魏宇明",18));list.add(new Student("蔡林虎",21));list.add(new Student("袁新槐",19));System.out.println("对象集合排序前:"+list);Collections.sort(list);System.out.println("对象集合排序后:"+list);}}
二、Comparator接口:
应用场景
1、我们若需要对一个对象进行排序,而该类没有实现Comparable接口。
2、如果引用的为第三方jar包,这时候,没办法改变类本身,可是使用这种方式。
介绍
1、Comparator是一个专用的比较器,当这个对象不支持自比较或者比较函数不能满足要求时,可些一个比较器来完成两个对象之间的排序问题。
2、Comparator体现了一种策略模式,就是不改变对象自身,而用一个策略对象来改变它的行为。
/*** 实体类*/public class Person{String name;int age;}/*** 单独实现类(通过年龄进行排序)*/public class PersonComparatorByAge implements Comparator<Person> {@Overridepublic int compare(Person o1, Person o2) {return o1.getAge()-o2.getAge();}}/*** 测试类*/public class ComparatorTest{public static void main(String[] args){List<Person> list=new ArrayList<>();list.add(new Person("魏宇明",18));list.add(new Person("蔡林虎",21));list.add(new Person("袁新槐",19));list.add(new Person("马鱼洪",20));System.out.println("对象集合排序前:"+list);// 方式一(调用定义好的实现类)Collections.sort(list,new PersonComparatorByAge());// 方式二(使用匿名类代替单独的类)list.sort(new Comparator<Person>(){@Overridepublic int compare(Person o1, Person o2) {return o1.getAge()-o2.getAge();}});System.out.println("对象集合排序后:"+list);}}
三、总结
Comparable和Comparator区别
1、Comparable是内部比较器Comparator是外部比较器
2、Comparable是排序接口,若一个类实现了Comparable接口,该类就支持对象排序;Comparator是比较器,需要控制某类的次序,可以建立一个该类的比较器进行排序。
