Iterating Over a List with a For-Each Loop
The for-each loop
examines the values of the list in order one at a time. The expression is defined in the following format: for (TypeOfVariable nameOfVariable: nameOfList)
, where TypeOfVariable
is the list’s element type, and nameOfVariable
is the variable that is used to store each value in the list as we go through it.
ArrayList<String> teachers = new ArrayList<>();
teachers.add("Eva");
teachers.add("Simon");
teachers.add("Tom");
for (String teacher: teachers) {
System.out.println(teacher);
}
The for-each loop described above hides some parts of the for-loop we practiced earlier. The for-each loop would look like this if implemented as a for-loop:
ArrayList<String> teachers = new ArrayList<>();
teachers.add("Eva");
teachers.add("Simon");
teachers.add("Tom");
for (int i = 0; i < teachers.size(); i++) {
String teacher = teachers.get(i);
// contents of the for each loop:
System.out.println(teacher);
}
Reference:
My site is free of ads and trackers. Was this post helpful to you? Why not
Disqus is great for comments/feedback but I had no idea it came with these gaudy ads.