Java: 迭代集合的最佳方式(这里是 ArrayList)

今天我正在愉快地编写代码,突然发现了一段我已经用了几百次的代码:

迭代集合(这里是数组列表)

出于某种原因,我实际上查看了 Eclipse 的自动完成选项,它让我想知道:

下列哪些循环比其他循环更适合使用?

经典的数组索引循环:

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

迭代器 hasNext ()/next () :

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

我的最爱,因为它写起来很简单:

for (iterable_type iterable_element : collection) {


}
254764 次浏览

All of them have there own uses:

  1. If you have an iterable and need to traverse unconditionally to all of them:

    for (iterable_type iterable_element : collection)

  2. If you have an iterable but need to conditionally traverse:

    for (Iterator iterator = collection.iterator(); iterator.hasNext();)

  3. If data-structure does not implement iterable:

    for (int i = 0; i < collection.length; i++)

None of them are "better" than the others. The third is, to me, more readable, but to someone who doesn't use foreaches it might look odd (they might prefer the first). All 3 are pretty clear to anyone who understands Java, so pick whichever makes you feel better about the code.

The first one is the most basic, so it's the most universal pattern (works for arrays, all iterables that I can think of). That's the only difference I can think of. In more complicated cases (e.g. you need to have access to the current index, or you need to filter the list), the first and second cases might make more sense, respectively. For the simple case (iterable object, no special requirements), the third seems the cleanest.

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.

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

The first option is better performance wise (As ArrayList implement RandomAccess interface). As per the java doc, a List implementation should implement RandomAccess interface if, for typical instances of the class, this loop:

 for (int i=0, n=list.size(); i < n; i++)
list.get(i);

runs faster than this loop:

 for (Iterator i=list.iterator(); i.hasNext(); )
i.next();

I hope it helps. First option would be slow for sequential access lists.

Here is an example

Query query = em.createQuery("from Student");
java.util.List list = query.getResultList();
for (int i = 0; i < list.size(); i++)
{


student = (Student) list.get(i);
System.out.println(student.id  + "  " + student.age + " " + student.name + " " + student.prenom);


}

There is additionally collections’ stream() util with Java 8

collection.forEach((temp) -> {
System.out.println(temp);
});

or

collection.forEach(System.out::println);

More information about Java 8 stream and collections for wonderers link