Difference between Comparable and Comparator?

后端 未结 3 1406
忘了有多久
忘了有多久 2021-01-21 04:07

My understand is Comparator can compare multiple objects from different classes while Comparable can only compare one onject with another instance in the same class.

C

3条回答
  •  执笔经年
    2021-01-21 04:16

    Not really.
    Comparable and Comparator are generic interfaces that allow to compare instances of the type defined in the generic (subclasses included).

    The main difference between them is that Comparable is directly implemented in the class which you want to compare objects.

    Consequently, if you have a single way to compare instances from a class, that is that you have a natural order for them, Comparable is the right approach.
    On the other hand, if you have multiple ways to compare instances from a class, Comparable is not enough.
    You should use Comparators instead (if it doesn't exist a natural order) or use both (if it exists a natural order and some other kinds of order).


    Example where Comparator can be useful in addition to Comparable :

    The String class implements Comparable by comparing two strings lexicographically. Suppose you need to sort a List of String according to a different rule : their length.
    You will need to define a Comparator that implements this rule such as :

    public class StringLengthComparator implements Comparator {
    
        @Override
        public int compare(String o1, String o2) {
            return Integer.compare(o1.length(), o2.length());
        }
    
    }
    

    Now you could sort Strings by using their natural order (using Comparable) :

    List strings = new ArrayList<>();
    ...
    strings.sort();
    

    But you could also use a specific Comparator :

    strings.sort(new StringLengthComparator());
    

    Or without creating any class with a lambda:

    strings.sort((o1,o2)->Integer.compare(o1.length(), o2.length()));
    

    Example where Comparator should be used instead of Comparable :

    Suppose you have an Account class that represents a bank account.
    Functionally you don't have a natural order to sort them but you have instead multiple orders according to the client needs. Making the class to implement Comparable would not make sense. But creating distinct Comparator would.


    Case where only Comparator can be used :

    If you want to define a order for instances of a class which you cannot change the source code (JDK class or third party class), Comparator is the way to follow.

提交回复
热议问题