Looping over a list
To go through every value in a list, loop over the indexes, from 0 to the last one. With a while loop:
ArrayList<String> chores = new ArrayList<>();
chores.add("sweep");
chores.add("dust");
chores.add("mop");
int index = 0;
while (index < chores.size()) {
System.out.println(chores.get(index));
index++;
}
sweep
dust
mopA for loop does the same with the counter in one line, and it's the usual way to write it:
ArrayList<String> chores = new ArrayList<>();
chores.add("sweep");
chores.add("dust");
chores.add("mop");
for (int i = 0; i < chores.size(); i++) {
System.out.println((i + 1) + ". " + chores.get(i));
}
1. sweep
2. dust
3. mop- The condition is
i < chores.size(), with<, because the last index issize() - 1. With<=, the loop would ask for one index too many and crash. - With
size()instead of a fixed number, the loop works for a list of any length. For an empty list it doesn't run at all. iis the index, sochores.get(i)is this round's value, andi + 1its place as people count it.
Other ranges
The loop's three parts can pick any part of the list. Starting at 1 skips the first value, i += 2 takes every second one, and starting at the last index and counting down goes through the list backwards:
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
numbers.add(50);
for (int i = 1; i < numbers.size(); i += 2) {
System.out.print(numbers.get(i) + " ");
}
System.out.println();
for (int i = numbers.size() - 1; i >= 0; i--) {
System.out.print(numbers.get(i) + " ");
}
System.out.println();
20 40
50 40 30 20 10Going backwards, the loop starts at size() - 1, the last index, and runs as long as i >= 0, so index 0 is included.
The next module shows the for-each loop: a shorter way to visit every value, for when you don't need the index.