Now, we will introduce a special kind of for loop called theΒ enhanced for loop. The enhanced for loop can be used to traverse through most data structures. Note that the enhanced for loop can only be used to traverse in the forward direction. To use it, we use this structure:
for (dataType i: arrayName) {
do something with i
}
This basically says that for every elementΒ iΒ in the array, we do something toΒ i.
We can only accessΒ i,Β but we cannot change or set new values toΒ i. Thus, we cannot do this:
/** Doubles each element of the array
*/
public static void doubleArray(int[] array) {
for (int i: array) {
i *= 2; // doubles each individual element
}
}
Why? Remember that Java is aΒ
pass-by-valueΒ programming language. The variableΒ
iΒ is only a copy of the actual element in the array and changingΒ
iΒ only changes the copy, not the actual element itself. If you want to actually change the array elements, use regular for loops as in
Topic 6.2.
However, we can use mutator methods on objects on the array to set the value of their instance variables. This is becauseΒ i is a copy of the object reference, which means thatΒ iΒ refers to the same object as the array element, so calling methods on i is the same as calling methods on the individual array elements themselves.
Here is an example of how we can use an enhanced for loop and mutator methods to set the value of an object's instance variables:
/** Represents a student
*/
public class Student {
private String name;
/** Sets the name of the Student
*/
public void setName(String name) {
this.name = name;
}
/** Other instance variables, methods, and constructors not shown
*/
}
// IN ANOTHER CLASS
/** Resets all students' names
*/
public static void doubleArray(Student[] array, String defaultName) {
for (Student student: array) {
student.setName(defaultName); // Sets each student's name to a default name
}
}
It's important to note that enhanced for loops force us to traverse through the entire data structure. We can't just go to every other element or every third element because we have no control over what indices of the array the loop uses.
Thus, while any enhanced for loop can be rewritten as a for loop or a while loop, there are for loop or while loop traversals that you cannot write as enhanced for loops.
Let's see how we could write the enhanced for loop above as a for loop:
// IN ANOTHER CLASS
/** Resets all students' names
*/
public static void doubleArray(Student[] array, String defaultName) {
for (int i = 0; i < array.length; i++) {
array[i].setName(defaultName); // Sets each student's name to a default name
}
}