Enhanced For Loops Over 2D Arrays

Part of: 2D Array

The For-Each Over a Grid. The enhanced for loop (for-each) also works on 2D arrays, but you must remember the array-of-arrays structure. The outer for-each gives you each row , which is itself a 1D array. A second, inner for-each then walks the elements of that row. The Critical Type Detail. The outer loop variable must be declared as a 1D array of the element type: - For int[][], the outer variable is int[] row and the inner is int value. - For String[][], the outer variable is String[] row and the inner is String s. Forgetting the brackets on the outer variable is the most common mistake. When to Use For-Each. The enhanced for loop is ideal when you only need to read every cell, because it is concise and avoids index bookkeeping. However, it has real limits: - You cannot know the current row or column index inside the loop. - You cannot reliably write back into the array through the loop variable for primitives, value = value 2; only changes the copy. What usually goes wrong. What you see What caused it How to fix it --- --- --- incompatible types: int[] cannot be converted to int The outer loop variable was declared int instead of int[] Each element of a 2D array is a whole row,

Challenge: Count Matches with For-Each