我看到
Comparable
接口(interface)只允许实现compareTo
方法。那么为什么我们需要这个接口(interface)呢?为什么我们不能简单地在任何我们想要的类中定义和声明该方法,而不必实现Comparable
接口(interface)?我明白这是正确的:
SortedSet<String> exampleSet = new TreeSet<String>();
<--TreeSet
实现SortedSet
界面。因此,如果我有一个名为“Date
”的类,它实现Comparable
,这是正确的吗:Comparable<Date> example = new Date<Date>();
。如果是,我到底能得到什么?我的意思是我得到什么样的对象?它有什么属性?如果没有,为什么不呢?
最佳答案
Why can't we simply define and declare the method in any class we want, without having to implement the Comparable interface?
在这种情况下,您希望排序方法如何工作?
能够对所有元素都可以相互比较的任何集合进行排序确实很方便 - 界面就是表达这一点的方式。
is this correct:
Comparable<Date> example = new Date<Date>();
不,除非 Date
本身是通用的。你可以写:
Comparable<Date> example = new Date();
...但这样做会很奇怪。通常Comparable
由想要比较现有对象的代码使用 - 例如,它会从集合中获取值并将它们相互比较。
关于java - 为什么 Java 'Comparable' 比仅使用 CompareTo 方法更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14760165/