Saturday, February 26, 2005

Iterators in Java

Coming from a background in C# for the past couple of years, I am so glad to see the Java SDK add constructs that I have used in the past.

In a personal project that I am working on, I had created a couple of enumeration classes.  The classes had a lookup() method that I used to allow me to assign a particular enumeration label to a variable by looking up a particular id of one of the enumeration constants.  To facilitate the lookup of a particular enumeration value, there was a private array of all the available enumerations in the particular class.  The lookup() method was pretty straight forward...


//.. lookup procedure expects an id pass in
for ( int i = 0; i < available.length; i++ ) {
    if ( available[i].getId() == id ) {
        return available[i];
    }
    return null;
}
I decided at work yesterday to come home and setup the latest milestone release of Eclipse so that I could play around with JDK 5.0.  After getting that working, I refactored my enumeration classes to be actual enum classes now that Java 5 has the new enum keyword.  With that refactoring, I was able to make use of the new for-each style of iteration that Java 5 has added.  So, my lookup() method on the enumeration classes now look like this...

//.. lookup procedure still expects an id passed in
MyEnumType[] available = MyEnumType.values();
for ( MyEnumType e : available ) {
    if ( e.getId() == id ) {
        return e;
    }
    return null;
}
I have been used to this style of construct in C# which has the for-each style of iterations for a collection.  For a new Java developer, this method might be a little harder to understand.  There is not the explicit notion of having checking each object in a particular collection like you have in C# where you say “for each ...”, but I feel like this is a little cleaner code than the style where you use the index property, which could always lead to problems itself.

Of course, Java had the older style of iterations where you could get an iterator and then calling hasNext() on each loop iteration, but it is a bit more to type and it is nice to have the compiler itself be a little smarter in situations like this where I am looping over a collection and checking every object in the collection.

Technorati Tags: , , ,

No comments: