利用Comparator排序

时间:2021-06-28 21:28:11

import java.util.Comparator;

class Studentxx {
    private String nameString;
    private int age;

    public Studentxx(String nameString, int age) {
        // super();
        this.nameString = nameString;
        this.age = age;
    }

    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof Studentxx)) {
            return false;
        }
        Studentxx studentxx = (Studentxx) obj;
        if (studentxx.nameString.equals(this.nameString)
                && studentxx.age == this.age) {
            return true;
        } else {
            return false;
        }
    }

    public String getNameString() {
        return nameString;
    }

    public void setNameString(String nameString) {
        this.nameString = nameString;
    }

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Studentxx [nameString=" + nameString + ", age=" + age + "]";
    }

}

class StudentComparator implements Comparator<Studentxx> {
    public int compare(Studentxx s1, Studentxx s2) {
        if (s1.equals(s2)) {
            return 0;
        } else if (s1.getAge() < s2.getAge()) {
            return 1;
        } else {
            return -1;
        }
    }
}

public class ComparatorDemo {
    public static void main(String[] args) {
        Studentxx stu[] = { new Studentxx("von", 20), new Studentxx("lee", 23),
                new Studentxx("wong", 29), new Studentxx("cong", 23),
                new Studentxx("sun", 39), new Studentxx("chao", 24) };
        java.util.Arrays.sort(stu, new StudentComparator());
        for (int i = 0; i < stu.length; i++) {
            System.out.println(stu[i]);
        }
    }
}

java.util.Arrays.sort(Studentxx[] a, Comparator<? super Studentxx> c):

Sorts the specified array of objects according to the order induced by the specified comparator. All elements in the array must be mutually comparable by the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the array).

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance.

Parameters:
a the array to be sorted
c the comparator to determine the order of the array. A null value indicates that the elements' natural ordering should be used.
Throws:
ClassCastException - if the array contains elements that are not mutually comparable using the specified comparator.

comparator和comparable两个接口都可以实现相投的排序功能,但是与comparable接口相比,comparator接口是一种补救的做法。