Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!eternal-september.org!feeder.eternal-september.org!mx04.eternal-september.org!.POSTED!not-for-mail From: Jim Janney Newsgroups: comp.lang.java.programmer Subject: Re: for :each style question Date: Wed, 14 Dec 2011 14:31:43 -0700 Organization: bent the bars the barest bit Lines: 41 Message-ID: <2pehw6alhc.fsf@shell.xmission.com> References: <30fdd7tlkkejm29ufduhc9nnfk7uu3c6h0@4ax.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx04.eternal-september.org; posting-host="PnllQd880uOddfy6hsxHuQ"; logging-data="3482"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/b1XL0QmksEcwh1neSGoi2" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:gVOdg/FnVVNjDdQNK1OGxnZ4/nU= sha1:XeZpUB5HNgTTyV8kfExEE7qil4Y= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:10747 Wanja Gayk writes: > In article , > 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? import org.apache.commons.lang.StringUtils; ... String joinedObjects = StringUtils.join(objects, ", "); Not to go all Lew on you here, but the Apache Commons stuff is worth a second look. -- Jim Janney