[英]Collections.sort between Directories and Files
我正在使用字符串Arraylist:ArrayList條目= new ArrayList(Arrays.asList(“”));
並動態地賦予價值。 它可能包含目錄或文件的名稱。
我需要在ListView中顯示條目,這樣,首先所有目錄都按排序順序顯示,然后文件按排序順序顯示。
這可能嗎? 如果是,有任何提示嗎? 感謝幫助..我正在使用
Collections.sort(entries); 對我的條目進行排序。
將2參數版本與自定義比較器一起使用。 比較如下:
boolean firstFileIsDirectory = file1.isDirectory();
boolean secondFileIsDirectory = file2.isDirectory();
if(firstFileIsDirectory && !secondFileIsDirectory){
return -1;
}
if(!firstFileIsDirectory && secondFileIsDirectory){
return 1;
}
return String.compare(filename1, filename2);
我已經做了。 使用的邏輯:將條目分成兩個ArrayList。 一個具有目錄其他文件。 分別對這兩個ArrayList進行排序。 最后將這兩個添加到“條目”中。 這是代碼:
private void sortEntries(String path){
ArrayList<String> entriesDir = new ArrayList<String>(Arrays.asList(""));
ArrayList<String> entriesFile = new ArrayList<String>(Arrays.asList(""));
entriesDir.removeAll(entriesDir);
entriesFile.removeAll(entriesFile);
int fileCounter=0, dirCounter=0;
path = path.equals("/") ? "" : path;
for(int i=1;i<=entries.size();i++){
if((new File(path+"/"+entries.get(i-1))).isFile()) entriesFile.add(fileCounter++, entries.get(i-1));
else entriesDir.add(dirCounter++, entries.get(i-1));
}
Collections.sort(entriesDir,String.CASE_INSENSITIVE_ORDER);
Collections.sort(entriesFile,String.CASE_INSENSITIVE_ORDER);
entries.removeAll(entries);
entries.addAll(entriesDir);
entries.addAll(entriesFile);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.