java - java 中的 Collections.sort 对于任何类

标签 java class sorting collections

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/

相关文章:

java - Android 应用程序未收到位置信息

java - JPA CriteriaBuilder 子查询多选

javascript - es6 类 - 将 boolean 值传递给构造函数

Java-如何在不扩展比较器的情况下对包含句点/点的字符串数组进行排序?

Java 删除 JTree 中 DefaultMutableTreenNode 上的 focusPainted

java - 在docker文件中下载open java sdk

c++ - '未定义对 Class::method() 的引用'

ios - 如何将我的 View 之一与 UIView 类连接?

python - 在 Python 字典中按值(降序)排序,然后按键(升序)排序

java - 按字符对数组中的字符串进行排序