我看到了一些关于 Java 中有错误的集合排序的问题。我显示的错误是这样的:
The method
sort(List<T>)
in the typeCollections
is not applicable for the arguments (ArrayList<Time>
)
我已经导入了 java.util.Collections 和 ArrayList。我还导入了我正在调用的类。这是我的代码:
在被调用的类中:
private ArrayList<Time> times;
...
public ArrayList<Time> getTimes() {
return this.times;
}
在我调用数组列表的类中:
public class TimeTUI {
private Scanner scan;
private TimeManager timeManager;
...
private ArrayList<Time> getSortedTimes() {
ArrayList<Time> sortedTimes = this.timeManager.getTimes();
Collections.sort(sortedTimes);
return sortedTimes;
}
错误出现在显示的行上:
Collections.sort(sortedTimes);
最佳答案
Time 类必须是 Comparable。
Collections.sort(List) 期望类 T 实现 Comparable 接口(interface)。如果你使用过许多内置类,你不会发现问题,但对于自定义类,sort 不知道如何对它们进行排序。因此,通过实现 Comparable 接口(interface),您可以定义方法 compareTo。
public class Time implements Comparable {
public int compareTo(Object o) {
// provide your logic of how to sort Time objects.
}
}
关于Java ArrayList 集合排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35803984/