简体   繁体   English

Java ArrayList集合排序

[英]Java ArrayList Collections sort

I've seen a few questions about the sort for collections having errors in Java. 我已经看到了一些有关Java出错的集合排序的问题。 The error I am showing is this: 我显示的错误是这样的:

The method sort(List<T>) in the type Collections is not applicable for the arguments ( ArrayList<Time> ) 类型Collections的方法sort(List<T>)不适用于参数( ArrayList<Time>

I have imported java.util.Collections and ArrayList. 我已经导入了java.util.Collections和ArrayList。 I also imported the class I am calling from. 我还导入了我要打电话的课程。 Here is my code: 这是我的代码:

In the class being called from: 在从中调用的类中:

private ArrayList<Time> times;

...

public ArrayList<Time> getTimes() {
        return this.times;
    }

In the class I am calling the array list to: 在类中,我将数组列表调用为:

public class TimeTUI {
    private Scanner scan;
    private TimeManager timeManager;

...

private ArrayList<Time> getSortedTimes() {
    ArrayList<Time> sortedTimes = this.timeManager.getTimes();
    Collections.sort(sortedTimes);
    return sortedTimes;
}

The error is appearing on the line showing: 错误显示在显示以下内容的行上:

Collections.sort(sortedTimes);

The class Time has to be a Comparable. 时间类必须是可比较的。

Collections.sort(List) expects that the class T implements Comparable interface. Collections.sort(List)期望类T实现Comparable接口。 If you have used many of the inbuilt classes, you wouldn't find problem, but for the custom classes sort doesn't know how to sort them. 如果您使用了许多内置类,则不会发现问题,但是对于自定义类,sort不知道如何对其进行排序。 So, by implementing Comparable interface, you give definition to a method compareTo. 因此,通过实现Comparable接口,可以为方法compareTo定义。

public class Time implements Comparable {
  public int compareTo(Object o) {
    // provide your logic of how to sort Time objects. 
   }
}

Your class type in the List or ArrayList must implement the Interface comparable and override properly the compareTo(...) method, 您在ListArrayList中的类类型必须实现comparable的接口,并正确覆盖compareTo(...)方法,

Is you break this contract and dont implement the interface. 您是否违反此合同并且不实现该接口。 the Class Collections has not a valid criteria/rule to compare/sort your list, and therefore your compiler will complain... 类集合没有有效的标准/规则来对列表进行比较/排序,因此您的编译器会抱怨...

I don't think that it is the ArrayList that is the issue here. 我不认为这是ArrayList。 For example: 例如:

ArrayList<String> names = new ArrayList<>();
...
Collections.sort(names);

works just fine. 效果很好。 The content of the list must be comparable so that the sort can work. 列表的内容必须具有可比性,这样排序才能起作用。 In this case the Time class and any sub-type must implement Comparable. 在这种情况下,Time类和任何子类型必须实现Comparable。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM