For-each loop vs. Iterator Handout Example of a for-each loop public class TestForEach public static void main(String [ J args) int [ J arr (1, 2, 3, 4,5,6, 7, 8) for (int i arr)//i is NOT an index: it's the value in a particular location // i holds the value of the current iteration's element arrli]- 0: for (int i: arr) System.out.printin(i): //variable i takes values in the array, one at a time, not an array index Eirst iteration (look at the first number) Second iteration (look at the second number) Third iteration (look at the third number) Fourth iteration (look at the fourth number) Fifth iteration (look at the fifth number) Sixth iteration (look at the sixth number) Seventh iteration (look at the seventh number) Eighth iteration (look at the eighth number) For-each loop is useful when you need only the values of the array. Do NOT use a for-each: If you need to change the contents of an array element: might not change it correctly If you need to access sOME of the array elements, but not all of them If you need to work through the array elements in reverse order If you need to simultaneously work with two or more arrays within a loop If you need to refer to the index of a particular element - - - - - If any of these cases apply, then use a regular for loop for-each (definite iteration)- recall: compiler generates the iterator calls for you Process EVERY element WITHOUT removing an element Trying to remove() during an iteration causes a ConcurrentModificationException - - Iterator object (indefinite iteration) Use if you want to stop part way through Used with collections where indexed access is inefficient or impossible Used to remove an object from a collection during iteration and possibly change the element at that position Available for all collections Using an iterator, we don't need to know how the data structure (collection) is implemented