Welcome 微信登录

首页 / 操作系统 / Linux / Java 排序比较器(Android应用)

網上介紹的步驟很亂,現把自己實現的步驟記錄一下,以備後用,當然更希望能給學習JavaAndroid的朋友提供一個實用的方法。在項目工程中,我們會經常用到要把集合或者數組中的元素進行比較和排序。而Java提供的比較器給我們提供了一個很好的接口。下面是具體步驟:1.新建你要排序的List,具體實現為如:ArrayList,加入數據,這裡的數據是裡面要存放的對象,如我要對android的一些文件進行排序,就定義了:
private List<FileProperty> mFileList;mFileList = new ArrayList<FileProperty>();
2.以為我要對文件排序,所以我新建了一個類。
public class FileProperty {        File file;        public FileProperty(File file) {            super();            this.file = file;        }        public String getFileName() {            return file.getName();        }    }
對每一個文件都初始化該類,當然你也許有其他的需求,但大同小異,這裡只是提供一個範例,你學會了就好。3,接下來我們構造比較器。複寫比較器的Compare方法。
public class CompareFile implements Comparator<FileProperty> {        String oneFileName, anotherFileName;        int result;        @Override        public int compare(FileProperty object1, FileProperty object2) {            // TODO Auto-generated method stub            oneFileName = object1.getFileName();            anotherFileName = object2.getFileName();            switch (mSortMode) {                case MENU_SORT_BYNAME:                result = oneFileName.compareToIgnoreCase(anotherFileName);                break;            default:                break;            }            return result;        }
4.我們就可以用集合類的排序方法了。
Collections.sort(mFileList, new CompareFile());
若是數組的話:
Arrays.sort(數組, new CompareFile());
5.完成,測試!