Java:通过Collection(这里是ArrayList)迭代的最佳方式 [英] Java: Best way to iterate through an Collection (here ArrayList)

查看:175
本文介绍了Java:通过Collection(这里是ArrayList)迭代的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我很高兴地编码,当我得到一段代码我已经使用了几百次:

Today I was happily coding away when I got to a piece of code I already used hundreds of times:


迭代集合(这里是ArrayList)

Iterating through a Collection (here ArrayList)

因为某种原因,我实际上看看Eclipse的自动完成选项,它让我想:

for some reason, I actually looked at the autocompletion options of Eclipse and it got me wondering:

以下循环比其他循环更好地使用哪些情况?

循环:

for (int i = 0; i < collection.length; i++) {
  type array_element = collection.get(index);
}

迭代器hasNext()/ next():

The Iterator hasNext()/next():

for (Iterator iterator = collection.iterator(); iterator.hasNext();) {
  type type = (type) iterator.next();   
}

我最喜欢的,因为它很容易写:

And my favorite because its so simple to write:

for (iterable_type iterable_element : collection) {

}


推荐答案

当你需要元素的索引时,第一个是有用的。这基本上等同于 ArrayList s的其他两个变体,但如果使用 LinkedList ,它会真的很慢。

The first one is useful when you need the index of the element as well. This is basically equivalent to the other two variants for ArrayLists, but will be really slow if you use a LinkedList.

第二个是有用的,当你不需要元素的索引,但可能需要删除元素,因为你迭代。但这有一个缺点,是一个太详细的IMO。

The second one is useful when you don't need the index of the element but might need to remove the elements as you iterate. But this has the disadvantage of being a little too verbose IMO.

第三个版本是我首选的选择。它是短的,适用于所有情况下,你不需要任何索引或底层的迭代器(即你只访问元素,不删除它们或修改集合 - 这是最常见的情况)。

The third version is my preferred choice as well. It is short and works for all cases where you do not need any indexes or the underlying iterator (i.e. you are only accessing elements, not removing them or modifying the Collection in any way - which is the most common case).

这篇关于Java:通过Collection(这里是ArrayList)迭代的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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