Array Traversals · Traversals de Arrays
| English | Português |
|---|---|
| traversal/træˈvɜːsl/ | traversing |
| enhanced for loop/enˈhænst fɔː luːp/ | laço for melhorado |
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.
Visitando cada elemento
- Uma travessia 遍历 visita todos os elementos de um array, geralmente em ordem.
- O loop indexado padrão:
for (int i = 0; i < a.length; i++) { ... a[i] ... } ivaria de0alength - 1, entãoa[i]alcança cada elemento uma vez.- A travessia é a 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.
O loop for-each
- O loop for melhorado (for-each) 增强for循环 visita cada valor sem um índice:
for (int x : a) { ... x ... }—xpega o valor de cada elemento sucessivamente.- Mais limpo quando você precisa apenas dos valores, não de suas posições.
- Mas não pode alterar o array nem usar o í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
- Use o loop indexado quando precisar da posição
i, ou para modificar elementos. - Use o loop for-each quando precisar apenas ler cada valor.
a[i] = 0;precisa do loop indexado; somar valores pode usar for-each.- Ambos visitam todos os elementos — escolha o que se adapta à tarefa.
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.
Limites novamente
- A condição do loop indexado
i < a.lengthmantémiválida. i <= a.lengthultrapassa por uma unidade → ArrayIndexOutOfBoundsException.- O loop for-each não pode ir fora dos limites — ele gerencia o intervalo para você.
- Quando você escreve o índice manualmente, é responsabilidade sua manter os limites.
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.
O loop for-each lê valores mas não pode atribuir de volta ao array. for (int x : a) { x = 0; } altera apenas a cópia local x, não a — para zerar o array você precisa do loop indexado a[i] = 0;. Use for-each para ler, o loop indexado para modificar ou quando precisar da posição 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.
Duas formas de somar um array:
- Indexada:
for (int i = 0; i < a.length; i++) { sum += a[i]; } - For-each:
for (int x : a) { sum += x; } - Ambas dão o mesmo total; for-each é mais limpo quando o índice não é necessário.
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.
Uma travessia visita todos os elementos. O loop indexado (for (int i = 0; i < a.length; i++)) fornece a posição i e pode modificar a[i]; o loop for-each (for (int x : a)) lê limpiamente cada valor mas não pode alterar o array nem usar um índice. Escolha dependendo se precisa do índice ou de modificar.
Traversing an array to sum it · Percorrer um array para somá-lo
i visits each index; sum accumulates a[i] (here a = {10,20,30}). · i visita cada índice; sum acumula a[i] (aqui a = {10,20,30}).
The correct condition to traverse an array a with an index is... · A condição correta para percorrer um array a com um índice é...
Valid indices are 0..length-1, so i < a.length. · Índices válidos são 0..length-1, então i < a.length.
Which loop should you use if you need to MODIFY the array elements? · Qual laço você deve usar se precisar MODIFICAR os elementos do array?
for-each can't assign back; use a[i] = ... with the indexed loop. · for-each não pode atribuir de volta; use a[i] = ... com o laço indexado.
In for (int x : a) { x = 0; }, the array a is set to all zeros. · Em for (int x : a) { x = 0; }, o array a é definido como todos zeros.
x is a local copy; the array is unchanged. · x é uma cópia local; o array permanece inalterado.
The for-each loop for (int x : a) is best when you only need to... · O laço for-each for (int x : a) é melhor quando você só precisa...
for-each cleanly reads values without an index. · for-each lê valores limpidamente sem um índice.
Visiting every element of an array is called a ___ (one word). · Visitar cada elemento de um array é chamado de ___ (uma palavra).
A traversal visits each element. · Um traversal visita cada elemento.