[英]Use of Comparator interface Java - Sort files
我有一個程序可以對計算機的特定目錄中的文件進行排序。 我正在使用Comparator界面並使用collections.sort-method,但是我無法從調用類訪問輸出。 我也不知道如何在“排序”類中對對象進行排序。
1)如果有人可以告訴我如何使用比較方法(原型為:sort(List list,Comparator c),會很高興
2)如何在目錄類中獲取輸出? 因為已對Sort-class進行了參數化,所以我無法訪問方法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.
}
首先第一件事情,如果你想Comparator
比較File
,然后告訴它:
public class Sort implements Comparator<File> {
@Override
public int compare(File n1, File n2){
return n1.getName().compareTo(n2.getName);
}
}
您在要求它比較自身的實例。 聲明Sort<File>
告訴編譯器您要一個泛型class
,而泛型類型參數恰好被稱為File
。 這與File
class
無關。
為了使用此Comparator
您需要做的是:
final File file = new File(System.getProperty(dir));
final File[] files = file.listFiles();
Arrays.sort(files, new Sort());
for(final File f : files) {
//do something with f
}
或者更好的是,只需使用一個匿名class
,這將防止您對Comparator
做任何奇怪的事情:
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return o1.getName().compareTo(o2.getName());
}
});
但是,如果您使用的是Java 8,則可以完全跳過此問題:
final Path path = Paths.get(System.getProperty(dir));
final List<Path> files = new ArrayList<>();
try (final DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
stream.forEach(files::add);
}
files.sort(Comparator.comparing(Path::getFileName));
現在您有了一個排序后的List<Path>
,您可以使用它進行任何操作。 例如,將排序后的列表打印到控制台:
files.forEach(System.out::println);
您只需要遍歷這些值,然后對這些值執行所需的任何任務。
因此,在您的示例中:
public void list(Comparator<File> sortOrder) {
Collections.sort(sort.arrayList, sortOrder);
// now - how do I get the sorted fileNames from here?
for (Sort<File> arrayList : file) {
System.out.println("Sorted list filenames: " + file.getName());
/* ... other actions ... */
}
}
只要已經實現了正確的通用比較器方法,就應該那么簡單
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.