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

查看:25
本文介绍了在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.

有人可以建议一种更简洁的方法吗(因为在处理集合时我不喜欢 indexed for loop),尽管它确实有效?

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

注意:我不能在 JDK 之外添加任何新的依赖项.

Note: I can't add any new dependencies outside the JDK.

推荐答案

试试这个:

// 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天全站免登陆