Joe Nuxoll's Weblog

« Previous day (Nov 7, 2005) | Main | Next day (Nov 9, 2005) »

20051108 Tuesday November 08, 2005

My favorite new Java language feature

    ArrayList<Donkey> donkeys = new ArrayList<Donkey>();
    ...
    for (Donkey d: donkeys) {
        d.doDonkeyStuff();
    }

The new simplified for loop construct is wonderful... but even better is the fact that you can create your *own* classes that leverage this new iterator type. All you have to do is declare a class (or interface) that implements (or extends if its an interface):

    java.lang.Iterable<T> or basically just Iterable<T>

If your class implements Iterable<Donkey>, then folks using your class can use the nifty new for syntax to automatically iterate each Donkey. Its beautiful and very elegant!

An example usage:

    public class Donkey {
        ...
    }

    public class DonkeyCorral implements Iterable<Donkey> {
        ...
        private ArrayList<Donkey> _storage = new ArrayList<Donkey>();
        ...
        // This example returns my generic storage collection's iterator,
        // though I could do whatever here...
        public Iterator<Donkey> iterator() {
            return _storage.iterator();
        }
        ...
    }

    DonkeyCorral corral = new DonkeyCorral();
    ...
    for (Donkey d: corral) {
        d.doDonkeyStuff();
    }

Thanks Tor - for setting me straight and fixing my code sample! That's what I get for going from memory and not looking at my own code while typing a blog entry!!! Hey! We need a blog entry module for NetBeans! I'd like to be able to blog from inside the tool! Get on that Tor!

( Nov 08 2005, 03:08:01 PM PST ) Permalink Comments [4]