What difference between Comparable and Compactor Interface ?
What
difference between Comparable and Compactor
Interface ?
Comparable
|
Comparator
|
It uses the compareTo() method.
int objectOne.compareTo(objectTwo).
|
It uses
the compare() method.
int compare(ObjOne, ObjTwo) |
It is necessary to modify the class whose instance is going to be
sorted.
|
A separate
class can be created in order to sort the instances.
|
Only one sort sequence can be created.
|
Many sort
sequences can be created.
|
It is frequently used by the API classes.
---------------------------------------------------------- java.lang.Comparable ------------------------------------------------------------ |
It used by
third-party classes to sort instances.
-------------------------------------------------------
java.util.Comparator
|
- If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified.
- Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable interface.
- If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Array.sort() method and object will be sorted based on there natural order defined by CompareTo method.
- Objects which implement Comparable in Java can be used as keys in a sorted map or elements in a sorted set for example TreeSet, without specifying any Comparator
What difference between Comparable and Compactor Interface ?
Reviewed by Mukesh Jha
on
1:37 AM
Rating:
No comments:
Add your comment