对于自己定义的数据结构,进行排序时,需要我们给予他一定的排序规则,这就涉及到了Java中的两个常用的接口Comparable<T>和Comparator<T>的实现。
1.comparable :可比较
又称为内部比较器,它是在你要排序的类中去实现comparable接口,重写compareTo方法,然后根据自定义规则来实现排序功能。
例:x.compareTo(y) 来比较x和y的大小,返回正数,意味着x大于y,若返回负数,意味着x比y小;返回零,意味着x等于y;
2.Comparator: 比较器
又称为外部比较器,不用在排序的类中实现,需要在使用Collections.sort(集合类,比较器)和Arrays.sort(数组,比较器)排序时,把这个比较器传入即可按照比较器规定的顺序排序。
public class ComparableDemo { static class AscComparator implements Comparator<Person>{ @Override public int compare(Person o1, Person o2) { return o1.getName().compareTo(o2.getName()); } } static class DescCompareator implements Comparator<Person>{ @Override public int compare(Person o1, Person o2) { return o2.getName().compareTo(o1.getName()); } } public static void main(String[] args) { // List<Person> list = new ArrayList<>(); list.add(new Person("ccc", 20)); list.add(new Person("AAA", 30)); list.add(new Person("bbb", 10)); list.add(new Person("ddd", 40)); for (Person p :list) { System.out.println("p = " + p); } Collections.sort(list,new AscComparator()); Collections.sort(list,new DescCompareator()); for (Person p :list) { System.out.println("p = " + p); } } } class Person implements Comparable<Person>{ @Override public int compareTo(Person o) { return this.name.compareTo(o.name); } private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } @Override public String toString() { return "Persion{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(Object obj) { return super.equals(obj); } }