What is the difference between Comparable and Comparator Interface?

2015-08-21 06:30:01 阅读( 7 )

2259人 收藏本页


Comparable interface shows that the class knows how to compare ITSELF
against another class.

Comparator interface allows a single class know how to compare two

The Comparable interface is (IMO) best used to implement a natural order
for lists of elements of the class. For example the low-to-high order of
numbers represented by the Integer class. This ties in nicely with the
order used by the variants of TreeSet, TreeMap, Arrays.sort() and
Collections.sort() where no Compataror is specified.

The Comparator interface is then used to create exotic orders, where
exotic is anything not implemented by the Comparable interface. This also
means the most obvious order for elements if a class doesn’t implement
Comparable, though a subclass may sometimes be a better choice then.


下一篇:What is Synchronized block and Synchronized Method? and Why we need those

上一篇:Can you suggest that what are points to be considered while doing Performance Tuning in Java?

亲~ 如果您有更好的答案 可在评论区发表您独到的见解。

您想查看更多的信息: 面试题