簡體   English   中英

對於API 9,按文件大小android的升序對文件列表進行排序

[英]Sort file list in ascending order of file size android for API 9

我已成功使用以下代碼對文件的Arraylist進行排序:

Comparator<File> stringLengthComparator = new Comparator<File>() {
                                        @Override
                                        public int compare(File o1, File o2) {
                                            return Integer.compare((int) (o1.length() / 1000),
                                                    (int) (o2.length() / 1000));
                                        }
                                    };

                                    Collections.sort(flLst, stringLengthComparator);

這對文件列表即flLst進行排序,但是唯一的問題是以上代碼需要API級別19和更高級別,而我當前的API最低要求是API級別9。我嘗試了以下操作,但無法交換文件:

for(x=0;x<flLst.size();x++)
                                        val1=flLst.get(x);
                                    for(x=0;x<flLst.size();x++)
                                    {
                                        for(int j=i;j<flLst.size();j++)
                                        {
                                            if(val1.length()>flLst.get(j).length())
                                            {
                                                temp=val1;
                                                val1=flLst.get(j);
                                                flLst.get(j)=temp;  // I get issue here as swapping file variables is not allowed this way
                                            }
                                        }

                                    }

我可以使用API​​ 9級的解決方案嗎?

如文檔中所述,Integer的compare()方法:

數字比較兩個int值。 返回的值與將返回的值相同:

 Integer.valueOf(x).compareTo(Integer.valueOf(y)) 

因此,您可以嘗試在API級別1中添加以下內容:

Comparator<File> stringLengthComparator = new Comparator<File>() {
    @Override
    public int compare(File o1, File o2) {
        return Integer.valueOf((int) (o1.length() / 1000)).compareTo(Integer.valueOf((int) (o2.length() / 1000)));
    }
};
Comparator<File> stringLengthComparator = new Comparator<File>() {
    @Override
    public int compare(File o1, File o2) {
        return o1.length() - o2.length();
    }
};

您的解決方案只是使事情變得過於復雜。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM