Here are main difference between Comparator and Comparable in Java :
1) Comparable is used to define natural order of object in Java e.g. numeric order for numbers, lexicographic order for String etc, and Comparator is used to define custom order which in addition of default ordering provided by Comparable e.g. default ordering for an Employee class could be by name or id, but you can provide additional Comparator to compare them by salary, age and branch.
2) Real use of Comparator and Comparable are in sorting list of object. Collections.sort() method is used to sort list of object and for sorting its required for them to implement either Comparator or Comparable interface.
3) Not significant but worth remember difference between these two is that Comparable is inside java.lang package while Comparator is inside java.util package.
4) If your object can be sorted in just one way then that order should be defined by Comparable but if you can sort object on multiple parameters then you can define multiple Comparators.
5) Another difference is the methods, Comparble uses compareTo() method to implement comparison logic while Comparator uses compare() method for same.
6) Comparators are generally implement using nested static class in Java, but from Java 8 you can also use lambda expression to implement Comparators for your object.
These were some difference between Comparator and Comparable in Java from my notes. Let me know if you come across any good difference between these two classes.
No comments:
Post a Comment