到底是什么的Collections.sort()
以下过载:Collections.sort()适用于Comparable或Comparator?
sort(List<T> list, Comparator<? super T> c)
的要求作为第二个参数?
例子:我开始为7个随机整数的列表:
List<Integer> listOfInts = new ArrayList<>();
Random rand = new Random(System.currentTimeMillis());
for (int i = 0; i < 7; i++) {
listOfInts.add(rand.nextInt());
}
然后我尝试使用Collections.sort()
作为对它们进行排序:
Collections.sort(listOfInts, Integer :: compare);
还有:
Collections.sort(listOfInts, Integer :: compareTo);
它们都是工作。 为什么不使用compareTo()
排序集合的调用会抛出/失败?compareTo()
的签名与compare()
的签名完全不同。
http://stackoverflow.com/questions/420223/what-is-the-difference-between-compare-and-compareto – msadler
我认为你会对Java 8中引入的lambdas有些困惑。尝试在Java 7中你将能够轻松看到它。 –
@msadler:给出相同答案的方法与方法相同。 'compare'比较两件事物,而在一件事物上调用'compareTo'来比较另一件事物。我已经在我的问题的最后一行提到了它。无论如何,谢谢你在这里链接这个答案。我在发布这个问题之前阅读了它,但它很好地链接了它。 – displayName