Java : What You Should Know about the Comparable and Comparator Interfaces
|
|
Comparable |
Comparator |
|
Interface |
Implemented
by the class being compared |
Separate
interface |
|
Purpose |
Defines
natural ordering for the class |
Defines
custom ordering for objects |
|
Method |
compareTo(Object obj): int |
compare(T obj1, T obj2): int |
|
Use
Case |
Sorting
objects based on inherent properties |
Sorting
objects based on custom criteria |
|
Usage |
Objects
implement Comparable
interface |
Custom
Comparator
instances are created |
|
Sorting |
Single
sorting criterion |
Multiple
sorting criteria |
|
Control |
Class
has control over its own ordering |
No
control over the class being compared |
|
Dependency |
Objects
must be modified to implement Comparable |
Objects
can be sorted without modification |
|
Returned
int indicates |
Negative
integer if calling object is less than specified object<br>Zero if they
are equal<br>Positive integer if calling object is greater than
specified object |
Negative
integer if obj1 is less than obj2<br>Zero if they are
equal<br>Positive integer if obj1 is greater than obj2 |
Thank you chatGPT
Comments
Post a Comment