Iterating over an ArrayList
Iterating Over an ArrayList
Using a For Loop
One way to iterate over the elements of an ArrayList is to use a for loop to iterate over the indices of the list. Since the indices of an ArrayList start at 0 and go to size() - 1, we will set up our for loop to count from 0 to size() - 1 .
ArrayList <Integer> grades = new ArrayList<>(Arrays.asList(80, 70, 90, 95));
for (int index = 0; index < grades.size(); index++) {
IO.println(grades.get(index));
}
Your Turn
Let's try it in the Java Playground.
- Predict the output.
- Run the code to determine if your prediction is correct.
- Modify the code so that each value in
grades is added to total.
- Predict the output and run your code to determine if it is correct.
- Modify the code so to compute the average of the values in
grades.
- Predict the output and run your code. The average should be
81.
Using an Enhanced For Loop to Iterate Over Values
An enhanced for loop can be used to iterate over all the values of the ArrayList instead of the indicies. Using the enhanced for loop means that the values are directly accessed without the need to use the get() method.
NOTE: You can not modify the values of an ArrayList using an enhanced for loop. If you want to modify the values, use a regular for loop or while loop structure.
The structure of an enhanced for loop to iterate over an ArrayList is as follows:
ArrayList<type of values> nameOfList - new ArrayList<>();
//statements to add values to the list
for (<type of values> variable : nameOfList) {
//whatever you want to do with the elements
}
Your Turn
Let's try it in the Java Playground.
- Predict the output.
- Run the code to determine if your prediction is correct.
- Modify the code so that each value in
grades is added to total.
- Predict the output and run your code to determine if it is correct.
- Modify the code so to compute the average of the values in
grades.
- Predict the output and run your code. The average should be
81.
Complete List of ArrayList Tutorials
Resources