As defined in JLS for-each loop can have two forms:
If the type of Expression is a subtype of
Iterable
then translation is as:List<String> someList = new ArrayList<String>(); someList.add("Apple"); someList.add("Ball"); for (String item : someList) { System.out.println(item); } // IS TRANSLATED TO: for(Iterator<String> stringIterator = someList.iterator(); stringIterator.hasNext(); ) { String item = stringIterator.next(); System.out.println(item); }
If the Expression necessarily has an array type
T[]
then:String[] someArray = new String[2]; someArray[0] = "Apple"; someArray[1] = "Ball"; for(String item2 : someArray) { System.out.println(item2); } // IS TRANSLATED TO: for (int i = 0; i < someArray.length; i++) { String item2 = someArray[i]; System.out.println(item2); }
Java 8 has introduced streams which perform generally better. We can use them as:
someList.stream().forEach(System.out::println);
Arrays.stream(someArray).forEach(System.out::println);