Array Traversals · Recorridos de Arreglos
| English | Español |
|---|---|
| traversal/træˈvɜːsl/ | recorrido |
| enhanced for loop/enˈhænst fɔː luːp/ | bucle for mejorado |
Visiting every element
- A traversal 遍历 visits every element of an array, usually in order.
- The standard indexed loop:
for (int i = 0; i < a.length; i++) { ... a[i] ... } isteps from0tolength - 1, soa[i]reaches each element once.- Traversal is the foundation of every array algorithm.
Recorriendo todos los elementos
- Una recorrida 遍历 visita cada elemento de un array, generalmente en orden.
- El bucle indexado estándar:
for (int i = 0; i < a.length; i++) { ... a[i] ... } iavanza desde0hastalength - 1, por lo quea[i]accede a cada elemento una sola vez.- La recorrida es la base de todo algoritmo de array.
The for-each loop
- The enhanced for loop (for-each) 增强for循环 visits each value without an index:
for (int x : a) { ... x ... }—xtakes each element's value in turn.- Cleaner when you only need the values, not their positions.
- But it can't change the array or use the index.
El bucle for-each
- El bucle enhanced for (for-each) 增强for循环 visita cada valor sin usar un índice:
for (int x : a) { ... x ... }—xtoma el valor de cada elemento sucesivamente.- Es más limpio cuando solo necesitas los valores, no sus posiciones.
- Sin embargo, no puede modificar el array ni utilizar el índice.
Indexed vs. for-each
- Use the indexed loop when you need the position
i, or to modify elements. - Use the for-each loop when you just need to read each value.
a[i] = 0;needs the indexed loop; summing values can use for-each.- Both visit every element — pick the one that fits the task.
Indexado vs. for-each
- Usa el bucle indexado cuando necesites la posición
i, o para modificar elementos. - Usa el bucle for-each cuando solo necesites leer cada valor.
a[i] = 0;requiere el bucle indexado; sumar valores puede usarse con for-each.- Ambos recorren todos los elementos: elige el que se adapte a la tarea.
Bounds again
- The indexed loop's condition
i < a.lengthkeepsivalid. i <= a.lengthoverruns by one → ArrayIndexOutOfBoundsException.- The for-each loop can't go out of bounds — it handles the range for you.
- When you write the index yourself, you own the bounds.
Límites nuevamente
- La condición del bucle indexado
i < a.lengthmantiene aidentro de límites válidos. i <= a.lengthexcede el límite en uno → ArrayIndexOutOfBoundsException.- El bucle for-each no puede desbordar límites: maneja el rango por ti.
- Cuando escribes el índice manualmente, tú eres responsable de los límites.
The for-each loop reads values but can't assign back into the array. for (int x : a) { x = 0; } changes only the local copy x, not a — to zero out the array you need the indexed loop a[i] = 0;. Use for-each to read, the indexed loop to modify or when you need the position i.
El bucle for-each lee valores pero no puede asignarlos de vuelta al array. for (int x : a) { x = 0; } cambia solo la copia local x, no a — para poner a cero el array necesitas el bucle indexado a[i] = 0;. Usa for-each para leer, el bucle indexado para modificar o cuando necesites la posición i.
Two ways to sum an array:
- Indexed:
for (int i = 0; i < a.length; i++) { sum += a[i]; } - For-each:
for (int x : a) { sum += x; } - Both give the same total; for-each is cleaner when the index isn't needed.
Dos formas de sumar un array:
- Indexado:
for (int i = 0; i < a.length; i++) { sum += a[i]; } - For-each:
for (int x : a) { sum += x; } - Ambas dan el mismo total; for-each es más limpio cuando no se necesita el índice.
A traversal visits every element. The indexed loop (for (int i = 0; i < a.length; i++)) gives the position i and can modify a[i]; the for-each loop (for (int x : a)) cleanly reads each value but can't change the array or use an index. Choose by whether you need the index or to modify.
Una recorrida visita cada elemento. El bucle indexado (for (int i = 0; i < a.length; i++)) proporciona la posición i y puede modificar a[i]; el bucle for-each (for (int x : a)) lee limpiamente cada valor pero no puede cambiar el array ni usar un índice. Elige según si necesitas el índice o modificarlo.
Traversing an array to sum it · Recorrer un arreglo para sumarlo
i visits each index; sum accumulates a[i] (here a = {10,20,30}). · i visita cada índice; sum acumula a[i] (aquí a = {10,20,30}).
The correct condition to traverse an array a with an index is... · La condición correcta para recorrer un arreglo a con un índice es...
Valid indices are 0..length-1, so i < a.length. · Los índices válidos son 0..length-1, por lo tanto i < a.length.
Which loop should you use if you need to MODIFY the array elements? · ¿Qué bucle debería usar si necesita MODIFICAR los elementos del arreglo?
for-each can't assign back; use a[i] = ... with the indexed loop. · for-each no puede asignar de vuelta; use a[i] = ... con el bucle indexado.
In for (int x : a) { x = 0; }, the array a is set to all zeros. · En for (int x : a) { x = 0; }, el arreglo a se establece en todos ceros.
x is a local copy; the array is unchanged. · x es una copia local; el arreglo permanece sin cambios.
The for-each loop for (int x : a) is best when you only need to... · El bucle for-each for (int x : a) es mejor cuando solo necesita...
for-each cleanly reads values without an index. · for-each lee valores limpiamente sin necesidad de un índice.
Visiting every element of an array is called a ___ (one word). · Visitar cada elemento de un arreglo se llama ___ (una palabra).
A traversal visits each element. · Un recorrido visita cada elemento.