java array iteration
Java5 now has language support for iteration of the form:
for (Type var : someIterable) { ... }
As well, there is now an Iterable<t> interface, and Arrays are directly iterable, allowing you to write:
String[] thingys = {"a","b","c"}; for (String thingy : thingys) { ... }
At work, we have a collection of utility iterators, most written before these were available. As such, we have an ArrayIter utility, and a ZipIterator, inspired by Python’s itertools.izip.
I’ve been going through these classes and their usages on a lazy basis to update them to the new syntax. I finally got around to a usage of the ZipIterator, which happened to compose an ArrayIter … it zipped together an array of String names with the results of a test.
So, I changed it to:
String[] names = { "foo", "bar", "baz" }; List results; for (Object[] pair : new ZipIterator(names, results)) { // ...
No dice, says Java:
/home/jsled/stuff/work/[...]TestMumble.java:46: cannot find symbol symbol : constructor ZipIterator(java.lang.String[],java.util.List)
location: class com.spokesoftware.util.iterator.ZipIterator
for (Object pairObj : new ZipIterator(data, results))
WTF? Okay, let me help you out:
for (Object[] pair : new ZipIterator((Iterable)names, results)) // ...
FUCK YOU, says Java:
/home/jsled/stuff/work/[...]/TestMumble.java:46: inconvertible types
found : java.lang.String[]
required: java.lang.Iterable
for (Object pairObj : new ZipIterator((Iterable)data, results))
It turns out that the string “iter” isn’t even in the text of the section about Arrays in the Java Language Spec. Array instances aren’t Iterable. They’re a special case in the handling of the for-each loop syntax.
This code ended up as:
for (Object pair : new ZipIterator(Arrays.asList(names), results))
Java is totally shitrude.
edit 2009-10-10: added some formatting/syntax highlighting of the java blocks