微信

使用微信服务,更方便

职友集>Java面试题 > What is the difference between Comparable and Comparator Interface?

What is the difference between Comparable and Comparator Interface?

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

2140人 收藏本页

标签:Java面试题

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.

来自IT公司面试手册

下一篇: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?

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

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