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

23

我正在开发Android应用,我从文件夹中读取文件并将其放入列表中。

该列表有两个值:1.名称 2.时间

可以使用以下代码显示列表:

 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);
 }

而日志如下:

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

从日志中可以看到,最早的时间在第一个对象。但我想要倒转它们的顺序。

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


你想要排序还是只是反转顺序? - Tommaso Bertoni
抱歉,我的错,我只是想把它的顺序反过来。 - Wun
2个回答

66

使用 Collections.reverse:

List myOrderedList = new List(); // any implementation
Collections.reverse(myOrderedList);
// now the list is in reverse order

另外,如果你是将元素添加到列表中的人,你可以在列表顶部添加新项,这样以后就不必反转它了:

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]

2
对于集合的使用,我认为第二个建议会导致太多不必要的开销,如果你正在使用ArrayList,它将复制所有先前的项目到一个新数组中,并将新项目预置到其中。但是,如果您使用LinkedList,则可以毫不担心地使用add(0,x)方法。 - npace
是的,我同意。这取决于列表如何在后续迭代中被处理以及其正确的实现方式。 - Tommaso Bertoni

0
创建一个HashMap的ArrayList,通过for循环将两个值放入其中。之后使用Collections.reverse()来反转你的数组值。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接