java - 我的 Comparable 实现出了点问题

标签 java collections iterable

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

我的问题是 Collections.sort 抛出错误,因为 只能迭代数组或 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;
    }
}

最佳答案

Collections.sort 返回 void。它不会为您返回排序后的集合。您可以在调用 sort 后简单地迭代集合本身:

Collections.sort(extsListed);
for (FileInfo info : extsListed) {
   ...

关于java - 我的 Comparable 实现出了点问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27886236/

相关文章:

.net - 类似于 IDictionary<TKey, TValue>,但仅适用于 .NET 中的键(不需要值)?

java - 实现 Java Iterable<E> 接口(interface)

java - 为什么这么多方法使用 Collection 而不是 Iterable?

java - 迭代器返回错误的整数值

java - 什么是可以在我的Web应用程序出现故障时通知我的工具或Tomcat配置?

java - SFTP Mule 客户端 Java API - 用户登录超时问题

java - 如何知道Windows XP中包含java运行时的目录?

java - org.omg.CORBA.Object objRef = orb.resolve_initial_references ("NameService"上出错);

python - Pharo 中的高性能 Python 集合

javascript - 删除 javascript map 的 forEach 循环中的条目是否安全?