如何在Android中反转列表的顺序?

Wun*_*Wun 12 android list

我在Android中开发,我从文件夹中读取文件并放入列表中.

该列表有两个值:1.Name 2.Time

它可以像下面的代码一样显示List:

 for(int i=0;i<fileList.size();i++){
        Log.i("DownloadFileListTask", "file mName("+i+") = " + fileList.get(i).mName);
        Log.i("DownloadFileListTask", "file mTime("+i+") = " + fileList.get(i).mTime);
 }
Run Code Online (Sandbox Code Playgroud)

日志如下:

file mName(0) = /DCIM/100__DSC/MOV_0093.LG1
file mTime(0) = 2015-04-15 14:47:46
file mName(1) = /DCIM/100__DSC/PICT0094.JPG
file mTime(1) = 2015-04-15 14:47:52
file mName(2) = /DCIM/100__DSC/MOV_0095.LG1
file mTime(2) = 2015-04-15 14:48:04
file mName(3) = /DCIM/100__DSC/MOV_0096.LG1
file mTime(3) = 2015-04-15 14:48:12
file mName(4) = /DCIM/100__DSC/MOV_0097.LG1
file mTime(4) = 2015-04-15 14:48:20
file mName(5) = /DCIM/100__DSC/MOV_0098.LG1
file mTime(5) = 2015-04-15 14:50:26
Run Code Online (Sandbox Code Playgroud)

从日志中,早期时间是第一个对象.但是我希望改变它的顺序.

如何在Android中反转列表的顺序?

Tom*_*oni 43

使用Collections.reverse:

List myOrderedList = new List(); // any implementation
Collections.reverse(myOrderedList);
// now the list is in reverse order
Run Code Online (Sandbox Code Playgroud)

此外,如果您是将元素添加到列表中的人,则可以在列表顶部添加新项目,以便稍后您不必反转它:

List<Integer> myOrderedList = new List<>(); // any implementation
myOrderedList.add(1); // adds the element at the end of the list
myOrderedList.add(0, 2); // adds the element (2) at the index (0)
myOrderedList.add(0, 3); // adds the element (3) at the index (0)
// the list is: [3, 2, 1]
Run Code Online (Sandbox Code Playgroud)

  • 集合用法的道具.我认为如果使用ArrayList,第二个建议会导致太多不必要的开销,因为它会将所有以前的项目复制到一个新项目中,并将新项目添加到其中.如果你正在使用LinkedList,你可以使用add(0,x)方法而不用担心. (2认同)