gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:40:19 24 4
gpt4 key购买 nike

所以我尝试使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com