Tuesday November 08, 2005
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]
Posted by Tor Norbye on November 08, 2005 at 08:43 PM PST #
Posted by Joe Nuxoll on November 09, 2005 at 12:37 AM PST #
Posted by fdasfdsa on October 12, 2006 at 07:20 PM PDT #
simplified for loop construct is wonderful... but even better is the
Posted by runescape money on November 10, 2007 at 12:56 AM PST #