Java for .net-guys or foreach in Java

Tags:
3 Comments »

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.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in