Traversing with the Enhanced For Loop

Part of: ArrayList

The for-each Loop The enhanced for loop (also called the for-each loop ) visits every element of an ArrayList without using an index. Its form is for (Type var : collection): Read this as: "for each name in names...". On each pass, name is automatically assigned the next element. It is cleaner and less error-prone than an indexed loop because there is no off-by-one risk. What You Can and Cannot Do The loop variable is a copy of the reference to each element. You can read it and call methods on it, but: - You cannot reassign the variable to change the list. name = "X"; only changes the local copy, not the list. - You cannot add or remove elements during a for-each loop. Doing so throws a ConcurrentModificationException. (We cover safe removal next lesson.) For changing elements by index, or removing during traversal, fall back to the indexed for loop. Summing with for-each Notice you can use int v because each Integer unboxes to an int automatically. When to Use Which Loop - for-each : best for reading every element in order. Concise and safe. - indexed for : needed when you require the index, modify by set, traverse backward, or remove elements. Summary The enhanced for loop is the

Challenge: Longest Word