我对Comparable的实现有些不对劲

dit*_*lav 2 java collections iterable

所以我正在尝试使用treeMap创建数据集合,然后我想在使用自己的比较器时得到一个排序列表.

我的问题是Collections.sort抛出错误,因为Can only iterate over an array or an instance of java.lang.Iterable我的extsListed是ArrayList类型,它确实是Iterable,可以在这里看到http://docs.oracle.com/javase/8/docs/api/java/util/List html的

    List<FileInfo> extsListed = new ArrayList<FileInfo>(exts.values());

    for (FileInfo info : Collections.sort(extsListed)) {
        System.out.println(info.key + ' ' + info.count + ' ' + info.size);
    }

    System.out.println(totalFound.toString() + ' ' + totalSize);
}

public static class FileInfo implements Comparable<FileInfo>{
    String key;
    Integer count;
    Long size;

    public FileInfo(String key, File file){
        count = 1;
        this.key = key;
        this.size = file.length();
    }

    public int compareTo(FileInfo other) {
        if (this.size > other.size) return 1;
        else if (this.size == other.size) {
            if (this.key.compareTo(other.key) >= 1) return 1;
            else if (this.key.equals(other.key)) return 0;
            else return -1;
        }
        else return -1;
    }
}
Run Code Online (Sandbox Code Playgroud)

man*_*uti 6

Collections.sort回报void.它不会为您返回已排序的集合.调用后,您可以简单地遍历集合本身sort:

Collections.sort(extsListed);
for (FileInfo info : extsListed) {
   ...
Run Code Online (Sandbox Code Playgroud)