What is the basic difference between comparable and comparators?

242    Asked by Unnatigautam in Java , Asked on Nov 17, 2023

I was enrolled in a Java Learning online course in which I have a problematic question regarding the difference between comparable and comparator. Therefore, can you provide me with the basic difference between these two in the context of Java? 

Answered by Chloe Burgess

 In the context of Java learning online the comparable and comparator are the interfaces that are used to shorten the objects, however, there are differences between both interfaces which are the following:-

  • Comparable Vs Comparators
  • Comparable Interface

It is mainly executed by the classes. It is used to define a natural ordering for its objects. It is also used for the default ordering not the objects. For example:-

Public class MyClass implements Comparable {
    @Override
    Public int compareTo(MyClass other) {
        // Implement comparison logic here
    }
}

Comparator Interface The compare method is another method used to shorten the objects. It is mainly implemented in a separate class. It can also be implemented as a lambda expression. For instance:-

Public class MyComparator implements Comparator {
    @Override
    Public int compare(MyClass obj1, MyClass obj2) {
        // Implement custom comparison logic here
    }
}

The comparable is used for the natural ordering in class, on the other hand comparator is used for control over the sorting of the logics.



Your Answer

Interviews

Parent Categories