Java类问题
在 C++ 中,如果我们向 vector 添加一些类对象,我们可以通过指定一些函数对列表进行排序,例如operator<()或operator==()或operator!=。
我们需要在java中做什么才能让Collections.sort按照我们的意愿工作
最佳答案
您实现 Comparable<T>
.
来自 Collections.sort
的文档:
Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).
或者,如果您不控制元素类型(例如,您有 List<String>
并且您想要应用自定义排序顺序),您可以实现 Comparator<T>
并将其作为额外参数传递给 Collections.sort
关于java - java 中的 Collections.sort 对于任何类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6830807/