Unit 4.4: Array Traversal
Array Traversal
Traversing an array occurs when repetition statements (loops) are used to access all or an ordered sequence of elements in an array.
- Traversal is the most common way to process data in an array, allowing you to examine, update, or aggregate every piece of information in the collection.
Indexed Loops
Traversing an array with an indexed for loop or while loop requires elements to be accessed using their indices.
- A loop control variable (like
i) acts as a pointer to the current element. This approach is necessary if you need to know the position of an element or modify specific indices.
Task: Using an indexed for loop to print all names in an array.
// In the main method ...
String[] names = {"Alice", "Bob", "Charlie"};
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
Enhanced for Loop (a.k.a. the for-each loop)
The enhanced for loop header includes a variable, referred to as the enhanced for loop variable. For each iteration of the loop, this variable is assigned a copy of an element without using its index.
The syntax of an enhanced for loop is:
for (declaration : expression) {
// Statements
}
- declaration: The newly declared block variable (the enhanced for loop variable), which must be of a type compatible with the elements of the array.
- expression: This evaluates to the array being traversed.
- The enhanced loop hides the index management, making code cleaner and reducing the risk of "off-by-one" errors. It should be used whenever you only need to read elements in sequence.
Task: Using an enhanced for loop to print names.
// In the main method ...
String[] names = {"Alice", "Bob", "Charlie"};
for (String name : names) {
System.out.println(name);
}
Modifying with Enhanced for Loop (Primitives)
Assigning a new value to the enhanced for loop variable does not change the value stored in the array. This is because the loop variable holds a copy of the element's value.
- In an enhanced loop, the block variable is local to the loop. Reassigning it only changes the local copy, leaving the original array data untouched.
Task: Attempting to double array values using an enhanced loop (fails).
// In the main method ...
int[] scores = {10, 20, 30};
for (int score : scores) {
score = score * 2; // Changes the copy, not the array element
}
// The array 'scores' remains {10, 20, 30}
Modifying with Enhanced for Loop (Objects)
When an array stores object references, the attributes of those objects can be modified by calling methods on the enhanced for loop variable.
- Although you cannot reassign the reference itself to a new object, you can "follow" the reference to update the object's internal data using its methods or fields.
Task: Updating object fields through an enhanced for loop.
// In the main method ...
class Student { public int score; }
Student[] students = { new Student(), new Student() };
students[0].score = 80;
students[1].score = 90;
for (Student s : students) {
s.score += 5; // This MODIFIES the internal state of the objects
// s = new Student(); // This would NOT replace the student in the array
}
// The scores of the students in the array are now 85 and 95.
Rewriting Loops
Code written using an enhanced for loop to traverse elements in an array can always be rewritten using an indexed for loop or a while loop.
- While any enhanced loop can be converted to an indexed loop, the reverse is not always true—specifically when index-specific logic is required.