【发布时间】:2015-02-21 10:02:27
【问题描述】:
我有一个程序可以对计算机某个目录中的文件进行排序。我正在使用 Comparator-interface 并使用 collections.sort-method 但我无法访问输出 - 从调用类。我也不知道如何对 Sort-class 中的对象进行排序。
1) 如果有人能告诉我如何使用比较方法会很高兴(原型是:sort(List list, Comparator c)
2) 如何获取目录类中的输出?因为排序类是参数化的,所以我无法访问方法 public String getName()
class 目录,创建 Sort 类的对象并将其放入 Arraylist(Sort 的成员)
private Sort sort = new Sort();
file = new File(System.getProperty(dir));
File[] files = getFiles(); // return only files, not directories;
for (int i = 0; i < files.length; i++) {
sort.arrayList.add(new Sort(files[i])); // put those in an ArrayList belonging to sort
}
list(sort); // call list-method
public void list(Comparator<File> sortOrder) {
Collections.sort(sort.arrayList, sortOrder);
// now - how do I get the sorted fileNames from here?
}
排序类
public class Sort<File> implements Comparator<Sort<File>> {
private File file;
public ArrayList <Sort> arrayList = new ArrayList <Sort> ();
public Sort(File file) {
this.file = file;
}
public Sort() {
}
public String getName() {
return this.file.toString();
}
// callback-method. Used when calling Collections.sort() in the other class.
public int compare(Sort<File> n1, Sort<File> n2){
// how do I sort objects on Filesnames.
}
【问题讨论】:
标签: java generics comparator