【问题标题】:How to reverse the order of list in Android?如何颠倒Android中的列表顺序?
【发布时间】:2015-06-21 00:49:43
【问题描述】:

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

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

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

 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中颠倒列表的顺序?

【问题讨论】:

  • 您要对其进行排序还是仅恢复其顺序?
  • 对不起,我只是想颠倒它的顺序。

标签: android list


【解决方案1】:

使用Collections.reverse:

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

另外,如果你是添加元素到列表的人,你可以add the new items at the top列表的,所以以后你不必反转它:

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]

【讨论】:

  • 集合使用的道具。如果您使用 ArrayList,我认为第二个建议会导致太多不必要的开销,因为它会将所有以前的项目复制到一个新数组中,并在其前面添加新项目。不过,如果您使用的是 LinkedList,则可以毫无顾虑地使用 add(0, x) 方法。
  • 是的,我同意。这取决于列表以后如何迭代以及它的正确实现。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 2018-01-05
    • 2018-04-15
    相关资源
    最近更新 更多