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

查看:114
本文介绍了Java:迭代集合的最佳方式(这里是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:

以下循环比其他循环使用的情况更好?

经典数组索引loop:

The classic array index loop:

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

Iterator 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 的其他两个变体,但如果使用 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:迭代集合的最佳方式(这里是ArrayList)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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