KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > lang > StringBuffer


1 /*
2  * @(#)StringBuffer.java 1.99 04/07/15
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package java.lang;
9
10 import sun.misc.FloatingDecimal;
11
12 /**
13  * A thread-safe, mutable sequence of characters.
14  * A string buffer is like a {@link String}, but can be modified. At any
15  * point in time it contains some particular sequence of characters, but
16  * the length and content of the sequence can be changed through certain
17  * method calls.
18  * <p>
19  * String buffers are safe for use by multiple threads. The methods
20  * are synchronized where necessary so that all the operations on any
21  * particular instance behave as if they occur in some serial order
22  * that is consistent with the order of the method calls made by each of
23  * the individual threads involved.
24  * <p>
25  * The principal operations on a <code>StringBuffer</code> are the
26  * <code>append</code> and <code>insert</code> methods, which are
27  * overloaded so as to accept data of any type. Each effectively
28  * converts a given datum to a string and then appends or inserts the
29  * characters of that string to the string buffer. The
30  * <code>append</code> method always adds these characters at the end
31  * of the buffer; the <code>insert</code> method adds the characters at
32  * a specified point.
33  * <p>
34  * For example, if <code>z</code> refers to a string buffer object
35  * whose current contents are "<code>start</code>", then
36  * the method call <code>z.append("le")</code> would cause the string
37  * buffer to contain "<code>startle</code>", whereas
38  * <code>z.insert(4, "le")</code> would alter the string buffer to
39  * contain "<code>starlet</code>".
40  * <p>
41  * In general, if sb refers to an instance of a <code>StringBuffer</code>,
42  * then <code>sb.append(x)</code> has the same effect as
43  * <code>sb.insert(sb.length(),&nbsp;x)</code>.
44  * <p>
45  * Whenever an operation occurs involving a source sequence (such as
46  * appending or inserting from a source sequence) this class synchronizes
47  * only on the string buffer performing the operation, not on the source.
48  * <p>
49  * Every string buffer has a capacity. As long as the length of the
50  * character sequence contained in the string buffer does not exceed
51  * the capacity, it is not necessary to allocate a new internal
52  * buffer array. If the internal buffer overflows, it is
53  * automatically made larger.
54  *
55  * As of release JDK 5, this class has been supplemented with an equivalent
56  * class designed for use by a single thread, {@link StringBuilder}. The
57  * <tt>StringBuilder</tt> class should generally be used in preference to
58  * this one, as it supports all of the same operations but it is faster, as
59  * it performs no synchronization.
60  *
61  * @author Arthur van Hoff
62  * @version 1.99, 07/15/04
63  * @see java.lang.StringBuilder
64  * @see java.lang.String
65  * @since JDK1.0
66  */

67  public final class StringBuffer
68     extends AbstractStringBuilder JavaDoc
69     implements java.io.Serializable JavaDoc, CharSequence JavaDoc
70 {
71
72     /** use serialVersionUID from JDK 1.0.2 for interoperability */
73     static final long serialVersionUID = 3388685877147921107L;
74
75     /**
76      * Constructs a string buffer with no characters in it and an
77      * initial capacity of 16 characters.
78      */

79     public StringBuffer() {
80     super(16);
81     }
82
83     /**
84      * Constructs a string buffer with no characters in it and
85      * the specified initial capacity.
86      *
87      * @param capacity the initial capacity.
88      * @exception NegativeArraySizeException if the <code>capacity</code>
89      * argument is less than <code>0</code>.
90      */

91     public StringBuffer(int capacity) {
92     super(capacity);
93     }
94
95     /**
96      * Constructs a string buffer initialized to the contents of the
97      * specified string. The initial capacity of the string buffer is
98      * <code>16</code> plus the length of the string argument.
99      *
100      * @param str the initial contents of the buffer.
101      * @exception NullPointerException if <code>str</code> is <code>null</code>
102      */

103     public StringBuffer(String JavaDoc str) {
104     super(str.length() + 16);
105     append(str);
106     }
107
108     /**
109      * Constructs a string buffer that contains the same characters
110      * as the specified <code>CharSequence</code>. The initial capacity of
111      * the string buffer is <code>16</code> plus the length of the
112      * <code>CharSequence</code> argument.
113      * <p>
114      * If the length of the specified <code>CharSequence</code> is
115      * less than or equal to zero, then an empty buffer of capacity
116      * <code>16</code> is returned.
117      *
118      * @param seq the sequence to copy.
119      * @exception NullPointerException if <code>seq</code> is <code>null</code>
120      * @since 1.5
121      */

122     public StringBuffer(CharSequence JavaDoc seq) {
123         this(seq.length() + 16);
124         append(seq);
125     }
126
127     public synchronized int length() {
128     return count;
129     }
130
131     public synchronized int capacity() {
132     return value.length;
133     }
134
135
136     public synchronized void ensureCapacity(int minimumCapacity) {
137     if (minimumCapacity > value.length) {
138         expandCapacity(minimumCapacity);
139     }
140     }
141
142     /**
143      * @since 1.5
144      */

145     public synchronized void trimToSize() {
146         super.trimToSize();
147     }
148
149     /**
150      * @throws IndexOutOfBoundsException {@inheritDoc}
151      * @see #length()
152      */

153     public synchronized void setLength(int newLength) {
154     super.setLength(newLength);
155     }
156
157     /**
158      * @throws IndexOutOfBoundsException {@inheritDoc}
159      * @see #length()
160      */

161     public synchronized char charAt(int index) {
162     if ((index < 0) || (index >= count))
163         throw new StringIndexOutOfBoundsException JavaDoc(index);
164     return value[index];
165     }
166
167     /**
168      * @since 1.5
169      */

170     public synchronized int codePointAt(int index) {
171         return super.codePointAt(index);
172     }
173
174     /**
175      * @since 1.5
176      */

177     public synchronized int codePointBefore(int index) {
178         return super.codePointBefore(index);
179     }
180
181     /**
182      * @since 1.5
183      */

184     public synchronized int codePointCount(int beginIndex, int endIndex) {
185     return super.codePointCount(beginIndex, endIndex);
186     }
187
188     /**
189      * @since 1.5
190      */

191     public synchronized int offsetByCodePoints(int index, int codePointOffset) {
192     return super.offsetByCodePoints(index, codePointOffset);
193     }
194
195     /**
196      * @throws NullPointerException {@inheritDoc}
197      * @throws IndexOutOfBoundsException {@inheritDoc}
198      */

199     public synchronized void getChars(int srcBegin, int srcEnd, char dst[],
200                                       int dstBegin)
201     {
202     super.getChars(srcBegin, srcEnd, dst, dstBegin);
203     }
204
205     /**
206      * @throws IndexOutOfBoundsException {@inheritDoc}
207      * @see #length()
208      */

209     public synchronized void setCharAt(int index, char ch) {
210     if ((index < 0) || (index >= count))
211         throw new StringIndexOutOfBoundsException JavaDoc(index);
212     value[index] = ch;
213     }
214
215     /**
216      * @see java.lang.String#valueOf(java.lang.Object)
217      * @see #append(java.lang.String)
218      */

219     public synchronized StringBuffer JavaDoc append(Object JavaDoc obj) {
220     super.append(String.valueOf(obj));
221         return this;
222     }
223
224     public synchronized StringBuffer JavaDoc append(String JavaDoc str) {
225     super.append(str);
226         return this;
227     }
228
229     /**
230      * Appends the specified <tt>StringBuffer</tt> to this sequence.
231      * <p>
232      * The characters of the <tt>StringBuffer</tt> argument are appended,
233      * in order, to the contents of this <tt>StringBuffer</tt>, increasing the
234      * length of this <tt>StringBuffer</tt> by the length of the argument.
235      * If <tt>sb</tt> is <tt>null</tt>, then the four characters
236      * <tt>"null"</tt> are appended to this <tt>StringBuffer</tt>.
237      * <p>
238      * Let <i>n</i> be the length of the old character sequence, the one
239      * contained in the <tt>StringBuffer</tt> just prior to execution of the
240      * <tt>append</tt> method. Then the character at index <i>k</i> in
241      * the new character sequence is equal to the character at index <i>k</i>
242      * in the old character sequence, if <i>k</i> is less than <i>n</i>;
243      * otherwise, it is equal to the character at index <i>k-n</i> in the
244      * argument <code>sb</code>.
245      * <p>
246      * This method synchronizes on <code>this</code> (the destination)
247      * object but does not synchronize on the source (<code>sb</code>).
248      *
249      * @param sb the <tt>StringBuffer</tt> to append.
250      * @return a reference to this object.
251      * @since 1.4
252      */

253     public synchronized StringBuffer JavaDoc append(StringBuffer JavaDoc sb) {
254         super.append(sb);
255         return this;
256     }
257
258
259     /**
260      * Appends the specified <code>CharSequence</code> to this
261      * sequence.
262      * <p>
263      * The characters of the <code>CharSequence</code> argument are appended,
264      * in order, increasing the length of this sequence by the length of the
265      * argument.
266      *
267      * <p>The result of this method is exactly the same as if it were an
268      * invocation of this.append(s, 0, s.length());
269      *
270      * <p>This method synchronizes on this (the destination)
271      * object but does not synchronize on the source (<code>s</code>).
272      *
273      * <p>If <code>s</code> is <code>null</code>, then the four characters
274      * <code>"null"</code> are appended.
275      *
276      * @param s the <code>CharSequence</code> to append.
277      * @return a reference to this object.
278      * @since 1.5
279      */

280     public StringBuffer JavaDoc append(CharSequence JavaDoc s) {
281         // Note, synchronization achieved via other invocations
282
if (s == null)
283             s = "null";
284         if (s instanceof String JavaDoc)
285             return this.append((String JavaDoc)s);
286         if (s instanceof StringBuffer JavaDoc)
287             return this.append((StringBuffer JavaDoc)s);
288         return this.append(s, 0, s.length());
289     }
290
291     /**
292      * @throws IndexOutOfBoundsException {@inheritDoc}
293      * @since 1.5
294      */

295     public synchronized StringBuffer JavaDoc append(CharSequence JavaDoc s, int start, int end)
296     {
297         super.append(s, start, end);
298         return this;
299     }
300
301     public synchronized StringBuffer JavaDoc append(char str[]) {
302         super.append(str);
303         return this;
304     }
305
306     public synchronized StringBuffer JavaDoc append(char str[], int offset, int len) {
307         super.append(str, offset, len);
308         return this;
309     }
310
311     /**
312      * @see java.lang.String#valueOf(boolean)
313      * @see #append(java.lang.String)
314      */

315     public synchronized StringBuffer JavaDoc append(boolean b) {
316         super.append(b);
317         return this;
318     }
319
320     public synchronized StringBuffer JavaDoc append(char c) {
321         super.append(c);
322         return this;
323     }
324
325     /**
326      * @see java.lang.String#valueOf(int)
327      * @see #append(java.lang.String)
328      */

329     public synchronized StringBuffer JavaDoc append(int i) {
330     super.append(i);
331         return this;
332     }
333
334     /**
335      * @since 1.5
336      */

337     public synchronized StringBuffer JavaDoc appendCodePoint(int codePoint) {
338     super.appendCodePoint(codePoint);
339     return this;
340     }
341
342     /**
343      * @see java.lang.String#valueOf(long)
344      * @see #append(java.lang.String)
345      */

346     public synchronized StringBuffer JavaDoc append(long lng) {
347         super.append(lng);
348     return this;
349     }
350
351     /**
352      * @see java.lang.String#valueOf(float)
353      * @see #append(java.lang.String)
354      */

355     public synchronized StringBuffer JavaDoc append(float f) {
356         new FloatingDecimal(f).appendTo(this);
357     return this;
358     }
359
360     /**
361      * @see java.lang.String#valueOf(double)
362      * @see #append(java.lang.String)
363      */

364     public synchronized StringBuffer JavaDoc append(double d) {
365         new FloatingDecimal(d).appendTo(this);
366     return this;
367     }
368
369     /**
370      * @throws StringIndexOutOfBoundsException {@inheritDoc}
371      * @since 1.2
372      */

373     public synchronized StringBuffer JavaDoc delete(int start, int end) {
374         super.delete(start, end);
375         return this;
376     }
377
378     /**
379      * @throws StringIndexOutOfBoundsException {@inheritDoc}
380      * @since 1.2
381      */

382     public synchronized StringBuffer JavaDoc deleteCharAt(int index) {
383         super.deleteCharAt(index);
384         return this;
385     }
386
387     /**
388      * @throws StringIndexOutOfBoundsException {@inheritDoc}
389      * @since 1.2
390      */

391     public synchronized StringBuffer JavaDoc replace(int start, int end, String JavaDoc str) {
392         super.replace(start, end, str);
393         return this;
394     }
395
396     /**
397      * @throws StringIndexOutOfBoundsException {@inheritDoc}
398      * @since 1.2
399      */

400     public synchronized String JavaDoc substring(int start) {
401         return substring(start, count);
402     }
403
404     /**
405      * @throws IndexOutOfBoundsException {@inheritDoc}
406      * @since 1.4
407      */

408     public synchronized CharSequence JavaDoc subSequence(int start, int end) {
409         return super.substring(start, end);
410     }
411
412     /**
413      * @throws StringIndexOutOfBoundsException {@inheritDoc}
414      * @since 1.2
415      */

416     public synchronized String JavaDoc substring(int start, int end) {
417         return super.substring(start, end);
418     }
419
420     /**
421      * @throws StringIndexOutOfBoundsException {@inheritDoc}
422      * @since 1.2
423      */

424     public synchronized StringBuffer JavaDoc insert(int index, char str[], int offset,
425                                             int len)
426     {
427         super.insert(index, str, offset, len);
428         return this;
429     }
430
431     /**
432      * @throws StringIndexOutOfBoundsException {@inheritDoc}
433      * @see java.lang.String#valueOf(java.lang.Object)
434      * @see #insert(int, java.lang.String)
435      * @see #length()
436      */

437     public synchronized StringBuffer JavaDoc insert(int offset, Object JavaDoc obj) {
438     super.insert(offset, String.valueOf(obj));
439         return this;
440     }
441
442     /**
443      * @throws StringIndexOutOfBoundsException {@inheritDoc}
444      * @see #length()
445      */

446     public synchronized StringBuffer JavaDoc insert(int offset, String JavaDoc str) {
447         super.insert(offset, str);
448         return this;
449     }
450
451     /**
452      * @throws StringIndexOutOfBoundsException {@inheritDoc}
453      */

454     public synchronized StringBuffer JavaDoc insert(int offset, char str[]) {
455         super.insert(offset, str);
456     return this;
457     }
458
459     /**
460      * @throws IndexOutOfBoundsException {@inheritDoc}
461      * @since 1.5
462      */

463     public StringBuffer JavaDoc insert(int dstOffset, CharSequence JavaDoc s) {
464         // Note, synchronization achieved via other invocations
465
if (s == null)
466             s = "null";
467         if (s instanceof String JavaDoc)
468             return this.insert(dstOffset, (String JavaDoc)s);
469         return this.insert(dstOffset, s, 0, s.length());
470     }
471
472     /**
473      * @throws IndexOutOfBoundsException {@inheritDoc}
474      * @since 1.5
475      */

476     public synchronized StringBuffer JavaDoc insert(int dstOffset, CharSequence JavaDoc s,
477                                             int start, int end)
478     {
479         super.insert(dstOffset, s, start, end);
480         return this;
481     }
482
483     /**
484      * @throws StringIndexOutOfBoundsException {@inheritDoc}
485      * @see java.lang.String#valueOf(boolean)
486      * @see #insert(int, java.lang.String)
487      * @see #length()
488      */

489     public StringBuffer JavaDoc insert(int offset, boolean b) {
490     return insert(offset, String.valueOf(b));
491     }
492
493     /**
494      * @throws IndexOutOfBoundsException {@inheritDoc}
495      * @see #length()
496      */

497     public synchronized StringBuffer JavaDoc insert(int offset, char c) {
498     super.insert(offset, c);
499     return this;
500     }
501
502     /**
503      * @throws StringIndexOutOfBoundsException {@inheritDoc}
504      * @see java.lang.String#valueOf(int)
505      * @see #insert(int, java.lang.String)
506      * @see #length()
507      */

508     public StringBuffer JavaDoc insert(int offset, int i) {
509     return insert(offset, String.valueOf(i));
510     }
511
512     /**
513      * @throws StringIndexOutOfBoundsException {@inheritDoc}
514      * @see java.lang.String#valueOf(long)
515      * @see #insert(int, java.lang.String)
516      * @see #length()
517      */

518     public StringBuffer JavaDoc insert(int offset, long l) {
519     return insert(offset, String.valueOf(l));
520     }
521
522     /**
523      * @throws StringIndexOutOfBoundsException {@inheritDoc}
524      * @see java.lang.String#valueOf(float)
525      * @see #insert(int, java.lang.String)
526      * @see #length()
527      */

528     public StringBuffer JavaDoc insert(int offset, float f) {
529     return insert(offset, String.valueOf(f));
530     }
531
532     /**
533      * @throws StringIndexOutOfBoundsException {@inheritDoc}
534      * @see java.lang.String#valueOf(double)
535      * @see #insert(int, java.lang.String)
536      * @see #length()
537      */

538     public StringBuffer JavaDoc insert(int offset, double d) {
539     return insert(offset, String.valueOf(d));
540     }
541
542     /**
543      * @throws NullPointerException {@inheritDoc}
544      * @since 1.4
545      */

546     public int indexOf(String JavaDoc str) {
547     return indexOf(str, 0);
548     }
549
550     /**
551      * @throws NullPointerException {@inheritDoc}
552      * @since 1.4
553      */

554     public synchronized int indexOf(String JavaDoc str, int fromIndex) {
555         return String.indexOf(value, 0, count,
556                               str.toCharArray(), 0, str.length(), fromIndex);
557     }
558
559     /**
560      * @throws NullPointerException {@inheritDoc}
561      * @since 1.4
562      */

563     public int lastIndexOf(String JavaDoc str) {
564         // Note, synchronization achieved via other invocations
565
return lastIndexOf(str, count);
566     }
567
568     /**
569      * @throws NullPointerException {@inheritDoc}
570      * @since 1.4
571      */

572     public synchronized int lastIndexOf(String JavaDoc str, int fromIndex) {
573         return String.lastIndexOf(value, 0, count,
574                               str.toCharArray(), 0, str.length(), fromIndex);
575     }
576
577     /**
578      * @since JDK1.0.2
579      */

580     public synchronized StringBuffer JavaDoc reverse() {
581     super.reverse();
582     return this;
583     }
584
585     public synchronized String JavaDoc toString() {
586     return new String JavaDoc(value, 0, count);
587     }
588
589     /**
590      * Serializable fields for StringBuffer.
591      *
592      * @serialField value char[]
593      * The backing character array of this StringBuffer.
594      * @serialField count int
595      * The number of characters in this StringBuffer.
596      * @serialField shared boolean
597      * A flag indicating whether the backing array is shared.
598      * The value is ignored upon deserialization.
599      */

600     private static final java.io.ObjectStreamField JavaDoc[] serialPersistentFields =
601     {
602         new java.io.ObjectStreamField JavaDoc("value", char[].class),
603         new java.io.ObjectStreamField JavaDoc("count", Integer.TYPE),
604         new java.io.ObjectStreamField JavaDoc("shared", Boolean.TYPE),
605     };
606
607     /**
608      * readObject is called to restore the state of the StringBuffer from
609      * a stream.
610      */

611     private synchronized void writeObject(java.io.ObjectOutputStream JavaDoc s)
612         throws java.io.IOException JavaDoc {
613         java.io.ObjectOutputStream.PutField fields = s.putFields();
614         fields.put("value", value);
615         fields.put("count", count);
616         fields.put("shared", false);
617         s.writeFields();
618     }
619
620     /**
621      * readObject is called to restore the state of the StringBuffer from
622      * a stream.
623      */

624     private void readObject(java.io.ObjectInputStream JavaDoc s)
625         throws java.io.IOException JavaDoc, ClassNotFoundException JavaDoc {
626         java.io.ObjectInputStream.GetField fields = s.readFields();
627         value = (char[])fields.get("value", null);
628         count = (int)fields.get("count", 0);
629     }
630 }
631
Popular Tags