java - Java 中的 Collections.sort()

标签 java list sorting object collections

我正在写一个 sortedAdd(T node) LinkedList 中的方法.我如何比较node.key_current.key_ ?我不能使用 < (升序),因为它是通用的。

public void sortedAdd(T node){
  ...
  Node<T> current = header;
  while (current != null) {
    if (node.key_ < current.key_) {
      ...
    }
  }
}

最佳答案

java.lang.Object实现 ComparableCollections.sort(List)期望 T 实现 Comparable。

From Collection.sort(List)

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.

我相信你的代码应该是:

 List<String> list = new ArrayList<String>();

关于java - Java 中的 Collections.sort(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15084671/

相关文章:

java - 在 java 8 中删除 JDBC ODBC 桥

java - Camunda 服务任务的 OptimisticLockingException

algorithm - 桶排序的近乎完美的分布模型

java - 为什么我得到 java.lang.ExceptionInInitializerError 以及如何摆脱它?

java - 对角处理二维数组

c++ - 维护一个有序的(通过参数,int)集合

python - 将对象列表的字符串表示形式转换回 python 中的列表

Linux:从txt列表中检查重复项

sorting - 如何自动对购物 list 进行排序? (朴素的机器学习)

string - 给定一个由 0 和 1 组成的循环字符串,求最小值。将所有 1 放在一起的相邻交换