Java enhanced for-loop FTW
r3dux | September 30, 2011I’ve got to do a whole slab of Java/J2EE coding soon so I’m in the process of skimming/re-acquainting myself with the Java language as a whole, when I just came across the new way to iterate over collections in a for-loop (available from Java 5 onwards) – and it’s genius!
public class ForLoopTest { public static void main(String[] args) { String[] carMakes = { "Ford", "Kia", "Vauxhall", "Ferrari" }; // Old-school for-loop System.out.println("----- Old-School For-Loop -----"); for (int loop = 0; loop < carMakes.length; loop++) { System.out.println(carMakes[loop]); } System.out.println(); // New enhanced style for-loop System.out.println("----- New Enhanced For-Loop -----"); for (String current : carMakes) { System.out.println(current); } } // End of main }
How much easier to both read and write is that? Clever clever clever…
P.S. I just looked it up and Java 5 was released in 2004, and it’s only now I’m finding out about this?! Hahaha! Besides a socket client I knocked together a couple of months back I haven’t coded anything in Java since 2001!











