1. //Comparable接口:
    2. //实现了Comparable接口的类的对象,
    3. //可被Collections.sort(List)方法和Arrays.sort(Object[])方法自动地排序。
    4. //实现该接口的方法可以作为SortedMap的key
    5. //或者SortedSet中的element,但是需要额外地声名一个Comparator
    6. public interface Comparable<T>{
    7. public int compareTo(T o);
    8. }

    Comparable是内部比较器,Comparator是外部比较器。

    以下为Comparable和Comparator的测试程序:

    1. import java.util.*;
    2. public class MainJava {
    3. public static void main(String[] args) throws Exception {
    4. ArrayList<Person> list=new ArrayList<>();
    5. list.add(new Person(20,"ccc"));
    6. list.add(new Person(30,"AAA"));
    7. list.add(new Person(10,"bbb"));
    8. list.add(new Person(40,"ddd"));
    9. System.out.println(list);
    10. Collections.sort(list);
    11. System.out.println(list);
    12. Collections.sort(list,new AscAgeComparator());
    13. System.out.println(list);
    14. Collections.sort(list,new DescAgeComparator());
    15. System.out.println(list);
    16. }
    17. private static class Person implements Comparable<Person>{
    18. public int age;
    19. public String name;
    20. public Person(int age, String name) {
    21. this.age = age;
    22. this.name = name;
    23. }
    24. @Override
    25. public String toString() {
    26. return name+"-"+ age;
    27. }
    28. boolean equals(Person person) {
    29. return (this.age==person.age)&&this.name.equals(person.name);
    30. }
    31. @Override
    32. public int compareTo(Person o) {
    33. return this.name.compareTo(o.name);
    34. }
    35. }
    36. private static class AscAgeComparator implements Comparator<Person>{
    37. @Override
    38. public int compare(Person o1, Person o2) {
    39. return o1.age-o2.age;
    40. }
    41. }
    42. private static class DescAgeComparator implements Comparator<Person>{
    43. @Override
    44. public int compare(Person o1, Person o2) {
    45. return o2.age-o1.age;
    46. }
    47. }
    48. }

    打印:

    1. [ccc-20, AAA-30, bbb-10, ddd-40]
    2. [AAA-30, bbb-10, ccc-20, ddd-40]
    3. [bbb-10, ccc-20, AAA-30, ddd-40]
    4. [ddd-40, AAA-30, ccc-20, bbb-10]
    5. Process finished with exit code 0