What is the difference between Comparable and Comparator Interface?

匿名网友 匿名网友 发布于: 2015-08-30 00:00:00
阅读 108 收藏 0 点赞 0 评论 0

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
classes.

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.

评论列表
文章目录