java – Ticklish Techs https://www.ticklishtechs.net a mostly .NET but also some other cool techs blog Thu, 13 Aug 2020 18:46:34 +0000 en-US hourly 1 https://wordpress.org/?v=5.7.11 Java for .net-guys or foreach in Java https://www.ticklishtechs.net/2009/04/28/java-for-net-guys-or-foreach-in-java/ https://www.ticklishtechs.net/2009/04/28/java-for-net-guys-or-foreach-in-java/#comments Tue, 28 Apr 2009 19:09:44 +0000 http://www.ticklishtechs.net/2009/04/28/java-for-net-guys-or-foreach-in-java/ Disclaimer: I’m absolutely not the person who can tell a lot about Java. I learned it a few years ago for university, but used it most of the time only for small example stuff. Never as deep as I’m working with .net. But maybe my newest discoveries are useful for more programmers with .net background.

I started using Java 1.4 and until last week I never took a look at Java 5 or 6. The only thing I was aware of were generics in Java.

iterators in Java

I was always annoyed in the missing of a foreach loop in Java. There is a concept of iterators in Java comparable to the .net Enumerators. But to loop over a list you will find in millions of Java programs the following code:

Iterator<Integer> i = list.iterator();
while(i.hasNext()) {
    Integer current = i.next();

    // do something with the current element
}

Sometimes build into a regular for loop, but I don’t think that is more readable or convenient:

for(Iterator<Integer> i = list.iterator(); i.hasNext(); ) {
    Integer current = i.next();

    // just do something
}

By the way: Can anyone tell me why the method is called iterator() and not getIterator() as used everywhere else in Java?

foreach in Java

With Java 5 (or 1.5 – call it as you like) a foreach loop was introduced. This is about five years ago, so I’m very fast in getting news from the Java world.

for(Integer i : list) {
    // just use i as the current element
}

I like it. It’s working for everything that implements java.lang.Iterable and for regular arrays.

]]>
https://www.ticklishtechs.net/2009/04/28/java-for-net-guys-or-foreach-in-java/feed/ 3