Difference between interfaces Comparable and Comparator? (Java) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Difference between interfaces Comparable and Comparator? (Java)

Main differences between them? Can be both applied simultaneously to the same class, or are exclusive (excludent?)?

18th Mar 2017, 1:49 PM
rarray
rarray - avatar
1 Answer
+ 5
A Comparable class can compare its instances. That is why you can use any sorting methods on this class instances. A Comparator is a class which can compare instances of an other class. Even if they are not Comparable. Using this method you can compare instances of any class. Of course a class can implement Comparable and Comparator too but it is useless as these two interfaces are totally different. You should never sort or compare Comparators.
18th Mar 2017, 2:12 PM
Tamás Barta
Tamás Barta - avatar