Hoy estaba felizmente codificando cuando llegué a un fragmento de código que ya usé cientos de veces:
Iterando a través de una colección (aquí ArrayList)
Por alguna razón, miré las opciones de autocompletado de Eclipse y me pregunto:
¿En qué casos es mejor utilizar los siguientes bucles que los demás?
El ciclo de índice de matriz clásico:
for (int i = 0; i < collection.length; i++) {
type array_element = collection.get(index);
}
El iterador tieneNext () / next ():
for (Iterator iterator = collection.iterator(); iterator.hasNext();) {
type type = (type) iterator.next();
}
Y mi favorito porque es muy sencillo de escribir:
for (iterable_type iterable_element : collection) {
}
for (Iterator<type> iterator = collection.iterator(); iterator.hasNext();) { type type = iterator.next(); }