简体   繁体   中英

Java ArrayList Collections sort

I've seen a few questions about the sort for collections having errors in 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> )

I have imported java.util.Collections and 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. 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. So, by implementing Comparable interface, you give definition to a method 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,

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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