Re: for :each style question
On 12/10/11 4:28 AM, Wanja Gayk wrote:
In article<iyBBq.2059$2e7.1155@newsfe18.iad>,
newsgroup.nospam@virtualinfinity.net says...
I find specific use-cases call for different approaches. For instance,
I like the following for string concatenation:
final StringBuilder builder = new StringBuilder();
String sep = "";
for (Object o: objects) {
builder.append(sep).append(o);
sep = ", ";
}
I always preferred to do it this way:
final StringBuilder builder = new StringBuilder();
final String sep = ", ";
for (final Object o: objects) {
builder.append(o).append(sep);
}
builder.setLength(Math.max(0,builder.length()-sep.length()));
The only drawback is that the size of the builder's internal buffer may
grow unnecessarily, if the last separator crosses its current bounds,
but how often does that happen and how often is it really a problem?
The *only* drawback? Having to invoke a "Math" command is a drawback
IMO. I like my approach because you can have a different starting
separator. Consider the case where you want parenthesis for one or
more items, but an empty string for no items.:
String ender = "";
String sep = "(";
for (Object o: objects) {
builder.append(sep).append(o);
sep=", "; end=")";
}
builder.append(end);
Builds a parenthesized comma-separated list. I have used this pattern
frequently for SQL or HQL query builders.