import java.util.Collection; import java.util.List; public class ForEachOverEmptyCollection { void testArray(int[][] arr) { if(arr.length != 0) return; for (int[] ints : arr) { System.out.println(ints.length); } } void testCollection(Collection c) { if(!c.isEmpty()) return; for (Object o : c) { System.out.println(o); } } void testArrayAfter(String[] arr) { int count = 0; boolean hasItem = false; for(String str : arr) { if(str != null) { count++; } hasItem = true; } if(arr.length == 0 && count > 0) { // count > 0 means we visited the loop -- impossible System.out.println("Impossible"); } if(!hasItem) { // we never visited the loop: array is empty System.out.println(arr[1]); } } void testCollectionAfter(List list) { boolean hasItem = false; String max = null; for (String s : list) { if(!hasItem || s.compareTo(max) > 0) { max = s; } hasItem = true; } if(!hasItem) { System.out.println( list.get(max == null ? 0 : 1)); } } }