反向遍历 ArrayList 最快、最有效的方法
有没有比使用 ListIterator 更快、更有效的方法?
ListIterator<Integer> itr = list.listIterator(list.size());
while(itr.hasPrevious()){
System.out.println(itr.previous());
}
Is there a quicker, more efficient means of doing so than using a ListIterator
?
ListIterator<Integer> itr = list.listIterator(list.size());
while(itr.hasPrevious()){
System.out.println(itr.previous());
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
根据
List
和ListIterator
的实现,以下操作可能会(稍微)更快。对于
ArrayList
来说,这可能会更快,但对于LinkedList
来说,几乎肯定会更慢。最好的选择是只使用迭代器。
几乎可以肯定的是,无论您在循环中做什么工作都会抵消不使用迭代器所获得的任何性能。
Depending on the implementation of the
List
andListIterator
the following may be (slightly) quicker.This may be faster for an
ArrayList
but it will almost certainly be slower for aLinkedList
.Your best bet is to just use the iterator.
It is almost certain that whatever work you are doing in the loop will negate any performance gained by not using the iterator.
理论上,使用简单的基于索引的 for 循环可能会快一点,因为测试没有方法调用开销,但实际上这非常非常不可能很重要,并且实际上可能根本不会显现出来。
更重要的是,基于迭代器的解决方案更加清晰,并且可以与链表(而不仅仅是 ArrayList)一起高效工作
Theoretically, using a simple index-based for loop could be faster by a miniscule amount since there is no method call overhead for the test, but in practice this is very, very unlikely to be significant and may not actually manifest at all.
It's far more important that the iterator-based solution is clearer and works efficiently with linked lists, not just ArrayLists
根据列表的实现类,反转列表(使用
Collections.reverse
)、使用前向迭代器,然后再次反转列表以恢复它可能会更有效。请注意,
java.util.LinkedList
是一个双链表,因此此策略不是必需的;使用hasPrevious
和previous
与向前移动一样高效。我认为,java.util 中的每个股票列表实现都是如此。Depending on the implementation class of the list, it may be more efficient to reverse the list (using
Collections.reverse
), use a forward iterator, and then reverse the list again to restore it.Note that
java.util.LinkedList
is a double-linked list, so this strategy isn't necessary; usinghasPrevious
andprevious
is just as efficient as going in the forward direction. This is true, I think, of every stock List implementation in java.util.您提出的解决方案与使用带有索引的常规 for 一样快。如果您希望寻找更好的解决方案,我建议使用 LinkedList 实现,因为我认为这是最快的解决方案。
The solution you presented is as fast as using a regular for with an index. If you wish to search for an even better solution, i suggest an implementation with LinkedList as i think that that is the quickest solution avaliable.
您可以通过一行来反转
Collections.reverse(list);
Output
You can reverse by one line that is
Collections.reverse(list);
Output