在java中以相反的顺序迭代列表 [英] Iterating through a list in reverse order in java

查看:207
本文介绍了在java中以相反的顺序迭代列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在迁移一段代码以利用泛型。这样做的一个参数是for循环比跟踪索引或使用显式迭代器更清洁。

I'm migrating a piece of code to make use of generics. One argument for doing so is that the for loop is much cleaner than keeping track of indexes, or using an explicit iterator.

在大约一半的情况下,列表ArrayList)正在以相反的顺序通过使用索引今天进行迭代。

In about half the cases, the list (an ArrayList) is being iterated in reverse order by using an index today.

有人可能建议一个更干净的方式这样做(因为我不喜欢索引

Can someone suggest a cleaner way of doing this (since I dislike the indexed for loop when working with collections), though it does work?

 for (int i = nodes.size() - 1; i >= 0; i--) {
    final Node each = (Node) nodes.get(i);
    ...
 }

推荐答案

尝试:

// Substitute appropriate type.
ArrayList<...> a = new ArrayList<...>();

// Add elements to list.

// Generate an iterator. Start just after the last element.
ListIterator li = a.listIterator(a.size());

// Iterate in reverse.
while(li.hasPrevious()) {
  System.out.println(li.previous());
}

这篇关于在java中以相反的顺序迭代列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆