Search code examples
javasortingcollectionscomparatorcomparable

What do you mean by you can create many sort sequences using Comparator in java?


In comparable ,Only one sort sequence can be created while in comparator many sort sequences can be created . what is sort sequence exactly means here.


Solution

  • Basically, a sort sequence is just an order relation (mathematically). It is a way of ranking objects.

    What it means is that when an Object implements the Comparable interface, only one order can be defined. Let's take a more concrete example with the custom class MyFile:

    public class MyFile implements Comparable<MyFile> {
        private String name;
        private Date creationDate;
        private String author;
    
        @Override
        public int compareTo(MyFile other) {
            return this.name.compareTo(other.name);
        }
    }
    

    In this example, the class MyFile implements the Comparable interface, which sorts a collection of MyFile by ascending name. It implements one sort sequence. But if you want to sort them by descending name ? Or by date ? Or by author ? Then you have to create different orderings. However, you cannot implement a second time the Comparable interface. This is when you create custom Comparator to have the behaviour you expect. Each Comparator implements a sort sequence.

    public class DateComparator implements Comparator<MyFile> {
    
        @Override
        public int compare(MyFile f1, MyFile f2) {
            return f1.getDate().compareTo(f2.getDate());
        }
    }
    
    public class ReverseNameComparator implements Comparator<MyFile> {
    
        @Override
        public int compare(MyFile f1, MyFile f2) {
            return f2.getName().compareTo(f1.getName());
        }
    }
    

    Those are two other sort sequence defined for the same class.