Here are the main difference between in Comparable and Comparator
1. Comparable belongs to java.lang.package
2. Comparable is by default uses by java collections to sort their element in sorted element.
3. Comparable has the method named compareTo which is use to compare two object and returns -1, +1
and o zero.
4. If we want to use comparable interface then the class
public int Object1.compareTo(Object2) ;
If object1 is less than object2 it will return -1, and if the object1 is greater than object2 then it will teturn +1 and if both are equal then it will return 0.
5. Suppose we have a class Employee and the employee has many details. But if we want to sort the Employee details according to their age using the collections then we have to implement the comparable in he employee class and override the compareTo method there. Means a class which want to be sorted using collections using comparable it must have to implement Comparable interface.
6. But using comparator we not need to implement the Comparator interface instead of this we can create an different java class that will help to sort the class (Employee)
1. Comparable belongs to java.lang.package
2. Comparable is by default uses by java collections to sort their element in sorted element.
3. Comparable has the method named compareTo which is use to compare two object and returns -1, +1
and o zero.
4. If we want to use comparable interface then the class
public int Object1.compareTo(Object2) ;
If object1 is less than object2 it will return -1, and if the object1 is greater than object2 then it will teturn +1 and if both are equal then it will return 0.
5. Suppose we have a class Employee and the employee has many details. But if we want to sort the Employee details according to their age using the collections then we have to implement the comparable in he employee class and override the compareTo method there. Means a class which want to be sorted using collections using comparable it must have to implement Comparable interface.
6. But using comparator we not need to implement the Comparator interface instead of this we can create an different java class that will help to sort the class (Employee)