【发布时间】:2025-11-25 15:40:02
【问题描述】:
所以我尝试使用 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;
}
}
【问题讨论】:
标签: java collections iterable