Si iterar la colección usando un iterador es más eficiente que la iteración normal

I have a collection like follows:

  final List list = new ArrayList(3);

Is it effecient to do something like below

    for (final Iterator iter = list.iterator(); iter.hasNext();)
    {
        // do something
    }

OR

for(final Object obj : list){
// do something 
}

?

preguntado el 09 de marzo de 12 a las 15:03

Usually code clarity is more important than worrying about performance. -

1 Respuestas

The second example is just a shortcut syntax for the first one. They're essentially the same thing (assuming you call final Object obj = iter.next(); en tu for círculo).

The shortcut syntax, known as "for-each" or "enhanced for", is more typically used since it's cleaner, more intuitive, and as Péter Török notes avoids potential bugs. I only recommend the plain syntax when it's needed for its greater flexibility.

Consulte este artículo para obtener más información: http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

contestado el 23 de mayo de 17 a las 11:05

Moreover, the second example is safer, as it avoids some potential bugs which may occur using the first form (especially in nested loops). - Péter Török

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.