Interface Comparator<T>

  • has only two methods: compare(object o1, object o2) & equals(object e)
  • java.util
class LengthComparator implements Comparator<String>{
    public int compare(String s1, String s2) {
        // <0: s1 ->s2
        // = 0: s1 == s2
        // >0: s2 -->s1
        //if need ascending order, then s1 - s2
        // if need descending order, then s2 - s1
        return s1.length() - s2.length();
    }
}

public class Example {
    public static void main(String[] args) {
        String[] strings = {"Foxtrot", "alpha", "echo", "golf",
 "bravo", "hotel", "Charlie", "DELTA"};
        Arrays.sort(strings, new LengthComparator);
    }
}

OR

public class Example {
    public static void main(String[] args) {
        String[] strings = {"Foxtrot", "alpha", "echo", "golf",
 "bravo", "hotel", "Charlie", "DELTA"};
        Arrays.sort(strings, new Comparator<String>() {
            public int compare(String s1, String s2) {
                return s1.length() - s2.length();
            }
        });
    }
}

Interface Comparable<T>

  • only one compareTo(T o) method
  • java.lang
class Movie implements Comparable<Movie>{
    int year;
    ...

    // sort based on the release of year
    public int compareTo(Movie m) {
        return this.year - m.year;
    }
    ...
}

Difference:

Comparator Comparable
Java Library java.util java.long
Implementation create a separate class implements it with the original class
target two objects current object with other objects
sort() method Collections.sort(object, comparator); Collections.sort(object);

*The compareTo() method implemented with Comparable interface becomes the natural ordering method for the class, so when invoke sort() method, don't need to pass in a new object.

String:

alphabetical order: return one.compareTo(two);

reverse alphabetical order: return two.compareTo(one);

results matching ""

    No results matching ""