Comparable接口的实现和使用

实现Comparable接口的compareTo方法 排序

该接口强行对实现它的每个类的对象进行整体排序。此排序被称为该类的自然排序 ,类的 compareTo 方法被称为它的自然比较方法 。实现此接口的对象列表(和数组)可以通过 Collections.sort (和 Arrays.sort )进行自动排序。如Jdk 中 Long 根据 value 大小进行排序


Long 类

    /**
     * Compares two {@code Long} objects numerically.
     *
     * @param   anotherLong   the {@code Long} to be compared.
     * @return  the value {@code 0} if this {@code Long} is
     *          equal to the argument {@code Long}; a value less than
     *          {@code 0} if this {@code Long} is numerically less
     *          than the argument {@code Long}; and a value greater
     *          than {@code 0} if this {@code Long} is numerically
     *           greater than the argument {@code Long} (signed
     *           comparison).
     * @since   1.2
     */
    public int compareTo(Long anotherLong) {
        return compare(this.value, anotherLong.value);
    }

    /**
     * Compares two {@code long} values numerically.
     * The value returned is identical to what would be returned by:
     * 
     *    Long.valueOf(x).compareTo(Long.valueOf(y))
     * 
* * @param x the first {@code long} to compare * @param y the second {@code long} to compare * @return the value {@code 0} if {@code x == y}; * a value less than {@code 0} if {@code x < y}; and * a value greater than {@code 0} if {@code x > y} * @since 1.7 */
public static int compare(long x, long y) { return (x < y) ? -1 : ((x == y) ? 0 : 1); }

Test.java

    public static void main(String[] args) {
        List longList = new ArrayList<>();
        longList.add(10L);//添加 并不会去排序
        longList.add(0L);
        longList.add(30L);
        longList.add(20L);


        System.out.println("sort before");
        for (Long l : longList) {
            System.out.println(l);
        }

        Collections.sort(longList);
        System.out.println("sort after");
        for (Long l : longList) {
            System.out.println(l);
        }
    }

运行结果如图:
Comparable接口的实现和使用_第1张图片

接下来 新建 Person 类,以age 属性进行排序

public class Person implements Comparable {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }


    @Override
    public int compareTo(Person o) {
        //比较此对象与指定对象的顺序。如果该对象小于、等于或大于指定对象,则分别返回负整数、零或正整数。
        return compare(this.age, o.age);
    }

    /**
     * @param age1
     * @param age2
     * @return
     */
    public static int compare(long age1, long age2) {
        return (age1 > age2 ? 1 :
                (age1 == age2 ? 0 : -1));
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Test.java

public static void main(String[] args) {
        Person person = new Person("小明",12);
        Person person2 = new Person("小红",11);
        Person person3= new Person("小宝",14);
        List personList = new ArrayList<>();
        personList.add(person);
        personList.add(person2);
        personList.add(person3);

        System.out.println("sort before");
        for (Person person1 : personList) {
            System.out.println(person1.toString());
        }

        Collections.sort(personList);
        System.out.println("sort after");
        for (Person person1 : personList) {
            System.out.println(person1.toString());
        }
    }

运行结果如图:

Comparable接口的实现和使用_第2张图片

so easy!

sort 原理

Collections.sort(..);

跟随jdk 源码,这里是jdk1.8.
ArrayList中的 default sort Method 还是 调用了Arrays.sort() 方法,

public static  void sort(T[] a, int fromIndex, int toIndex,
                                Comparatorsuper T> c) {
        if (c == null) {
            sort(a, fromIndex, toIndex);
        } else {
            rangeCheck(a.length, fromIndex, toIndex);
            if (LegacyMergeSort.userRequested)
                legacyMergeSort(a, fromIndex, toIndex, c);
            else
                TimSort.sort(a, fromIndex, toIndex, c, null, 0, 0);
        }
    }
public static void sort(Object[] a, int fromIndex, int toIndex) {
        rangeCheck(a.length, fromIndex, toIndex);
        if (LegacyMergeSort.userRequested)
            legacyMergeSort(a, fromIndex, toIndex);
        else
            ComparableTimSort.sort(a, fromIndex, toIndex, null, 0, 0);
    }

    /** To be removed in a future release. */
    private static void legacyMergeSort(Object[] a,
                                        int fromIndex, int toIndex) {
        Object[] aux = copyOfRange(a, fromIndex, toIndex);
        mergeSort(aux, a, fromIndex, toIndex, -fromIndex);
    }

源码中涉及排序的知识,以后再讲

最后

Comparable接口的实现和使用其实非常简单的,Jdk 都为我们实现了,我们了解原理及使用。

你可能感兴趣的:(Java)