Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: markspace Newsgroups: comp.lang.java.programmer Subject: Re: StringBuilder.append and CharSequence Date: Wed, 25 Sep 2013 18:34:14 -0700 Organization: A noiseless patient Spider Lines: 43 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Thu, 26 Sep 2013 01:34:18 +0000 (UTC) Injection-Info: mx05.eternal-september.org; posting-host="9185b88a2b5381a82810209530bb8295"; logging-data="10689"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/ZCXFICS4sMWV6/0rYZm5e1Z3/ROnWxGs=" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20130801 Thunderbird/17.0.8 In-Reply-To: Cancel-Lock: sha1:frJHpPhKzQsBDM9V/68H5rTR9Q4= Xref: csiph.com comp.lang.java.programmer:25345 On 9/25/2013 1:02 PM, markspace wrote: > On 9/25/2013 7:19 AM, Andreas Leitgeb wrote: >> Is it safe to use "stringBuilder.append(this);" > > It wasn't clear to me either from reading the Java docs that the above > was safe, so I'd avoid it. > >> in a CharSequence >> implementation's .toString(), or could this lead to a recursive >> loop, if some version of a Java class library implements the >> append() for CharSequence by using it's toString() ? > > That paragraph wasn't clear to me at all. I was going to suggest > toString() as the safe approach. > > stringBuilder.append( this.toString() ); > > This seems bomb proof to me, as the string is constructed before the > method call. Did I miss something? Actually, I mis-read your problem statement, I think. Having implemented a couple of CharSequence classes, the only rational approach would be to copy the chars out of a CharSequence one at a time with a loop and charAt(). toString() must create an immutable String and so must create a new buffer, so that's an extra buffer copy, which seems undesirable no matter who's implementing the append() method. However I wouldn't call toString(), as that would obviously create a stack overflow. I would think that you must have some much better method of copying characters though, as you should have access to your own private fields. @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append( myCharArray, start, length ); return sb.toString(); } This obviously could be done with a single "new String(..." but I'm just trying to hammer the idea home that there's internal fields to use.