September 13, 2003 00:15
Programming, Java
This has been bugging me for years. I've been writing code this way:

StringBuffer b = new StringBuffer();
for (int i = 0; i < stringList.length; i++)
{
    String element = strings[i];
    b.append(element);
    if (i < stringList.length) b.append(", ");
}

and thinking there must be a better way to add a comma so it didn't require a comparison on every element in the list.

Enter Spud. In this beautiful little post, he lays out the more elegant and efficient:

Writer out = ...;
List l = ...;
String sep = "";
for (Iterator i = l.iterator(); i.hasNext(); ) {
    String s = (String) i.next();
    out.write(sep);
    out.write(s);
    sep = ",";
}

« Reserved words in Firebird | Home | Logging with Eclipse »

I think the latter is less idiomatic and less clear. You have to stop and think above what is note that wierd side effect of changing the separator.

I think the top example (with the conditional changed to "if (i < 0)" and placed before printing the element) is clearer. I'm not sure what you have against the conditional, but if you really felt you need to remove it (performance?) then I'd unroll the 0 iteration of the loop (the special case) and then have the loop from 1 .. end. If you don't know the state of the list already, you have some non-loop conditionals to test for an empty list. Here is the uglier iterator form:

Iterator it_list = list.iterator();
if (it_list.hasNext() {
    out.write(it_list.next();
}

while (it_list.has_next() {
    out.write(sep);
    out.write(it_list.next());
}

Or, you can remove the if statement from the loop and add

if (b.length() > 1) b.setLength(b.getLength() - 2);

after the loop, effectively truncating the last ", "

Why not just:
Writer out = ...;
List l = ...;
for (Iterator i = l.iterator(); i.hasNext(); ) {
    out.write(i.next());
    if (i.hasNext()) out.write(",");
}

I do it the way Norman showed. Essentially, it always boils down to handling the first element specially, then adding separator/element pairs in a loop.

You can tell who comes from a procedural background. I still don't think it's a bad thing. :-)

name
url