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 = ",";
}
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()); }after the loop, effectively truncating the last ", "
Writer out = ...; List l = ...; for (Iterator i = l.iterator(); i.hasNext(); ) { out.write(i.next()); if (i.hasNext()) out.write(","); }You can tell who comes from a procedural background. I still don't think it's a bad thing. :-)