1 /* 2 * Copyright (c) 1994, 2012, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang; 27 28 29 /** 30 * A thread-safe, mutable sequence of characters. 31 * A string buffer is like a {@link String}, but can be modified. At any 32 * point in time it contains some particular sequence of characters, but 33 * the length and content of the sequence can be changed through certain 34 * method calls. 35 * <p> 36 * String buffers are safe for use by multiple threads. The methods 37 * are synchronized where necessary so that all the operations on any 38 * particular instance behave as if they occur in some serial order 39 * that is consistent with the order of the method calls made by each of 40 * the individual threads involved. 41 * <p> 42 * The principal operations on a {@code StringBuffer} are the 43 * {@code append} and {@code insert} methods, which are 44 * overloaded so as to accept data of any type. Each effectively 45 * converts a given datum to a string and then appends or inserts the 46 * characters of that string to the string buffer. The 47 * {@code append} method always adds these characters at the end 48 * of the buffer; the {@code insert} method adds the characters at 49 * a specified point. 50 * <p> 51 * For example, if {@code z} refers to a string buffer object 52 * whose current contents are {@code "start"}, then 53 * the method call {@code z.append("le")} would cause the string 54 * buffer to contain {@code "startle"}, whereas 55 * {@code z.insert(4, "le")} would alter the string buffer to 56 * contain {@code "starlet"}. 57 * <p> 58 * In general, if sb refers to an instance of a {@code StringBuffer}, 59 * then {@code sb.append(x)} has the same effect as 60 * {@code sb.insert(sb.length(), x)}. 61 * <p> 62 * Whenever an operation occurs involving a source sequence (such as 63 * appending or inserting from a source sequence), this class synchronizes 64 * only on the string buffer performing the operation, not on the source. 65 * Note that while {@code StringBuffer} is designed to be safe to use 66 * concurrently from multiple threads, if the constructor or the 67 * {@code append} or {@code insert} operation is passed a source sequence 68 * that is shared across threads, the calling code must ensure 69 * that the operation has a consistent and unchanging view of the source 70 * sequence for the duration of the operation. 71 * This could be satisfied by the caller holding a lock during the 72 * operation's call, by using an immutable source sequence, or by not 73 * sharing the source sequence across threads. 74 * <p> 75 * Every string buffer has a capacity. As long as the length of the 76 * character sequence contained in the string buffer does not exceed 77 * the capacity, it is not necessary to allocate a new internal 78 * buffer array. If the internal buffer overflows, it is 79 * automatically made larger. 80 * 81 * As of release JDK 5, this class has been supplemented with an equivalent 82 * class designed for use by a single thread, {@link StringBuilder}. The 83 * <tt>StringBuilder</tt> class should generally be used in preference to 84 * this one, as it supports all of the same operations but it is faster, as 85 * it performs no synchronization. 86 * 87 * @author Arthur van Hoff 88 * @see java.lang.StringBuilder 89 * @see java.lang.String 90 * @since JDK1.0 91 */ 92 public final class StringBuffer 93 extends AbstractStringBuilder 94 implements java.io.Serializable, CharSequence 95 { 96 97 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 98 static final long serialVersionUID = 3388685877147921107L; 99 100 /** 101 * Constructs a string buffer with no characters in it and an 102 * initial capacity of 16 characters. 103 */ 104 public StringBuffer() { 105 super(16); 106 } 107 108 /** 109 * Constructs a string buffer with no characters in it and 110 * the specified initial capacity. 111 * 112 * @param capacity the initial capacity. 113 * @exception NegativeArraySizeException if the {@code capacity} 114 * argument is less than {@code 0}. 115 */ 116 public StringBuffer(int capacity) { 117 super(capacity); 118 } 119 120 /** 121 * Constructs a string buffer initialized to the contents of the 122 * specified string. The initial capacity of the string buffer is 123 * {@code 16} plus the length of the string argument. 124 * 125 * @param str the initial contents of the buffer. 126 * @exception NullPointerException if {@code str} is {@code null} 127 */ 128 public StringBuffer(String str) { 129 super(str.length() + 16); 130 append(str); 131 } 132 133 /** 134 * Constructs a string buffer that contains the same characters 135 * as the specified {@code CharSequence}. The initial capacity of 136 * the string buffer is {@code 16} plus the length of the 137 * {@code CharSequence} argument. 138 * <p> 139 * If the length of the specified {@code CharSequence} is 140 * less than or equal to zero, then an empty buffer of capacity 141 * {@code 16} is returned. 142 * 143 * @param seq the sequence to copy. 144 * @exception NullPointerException if {@code seq} is {@code null} 145 * @since 1.5 146 */ 147 public StringBuffer(CharSequence seq) { 148 this(seq.length() + 16); 149 append(seq); 150 } 151 152 @Override 153 public synchronized int length() { 154 return count; 155 } 156 157 @Override 158 public synchronized int capacity() { 159 return value.length; 160 } 161 162 163 @Override 164 public synchronized void ensureCapacity(int minimumCapacity) { 165 if (minimumCapacity > value.length) { 166 expandCapacity(minimumCapacity); 167 } 168 } 169 170 /** 171 * @since 1.5 172 */ 173 @Override 174 public synchronized void trimToSize() { 175 super.trimToSize(); 176 } 177 178 /** 179 * @throws IndexOutOfBoundsException {@inheritDoc} 180 * @see #length() 181 */ 182 @Override 183 public synchronized void setLength(int newLength) { 184 super.setLength(newLength); 185 } 186 187 /** 188 * @throws IndexOutOfBoundsException {@inheritDoc} 189 * @see #length() 190 */ 191 @Override 192 public synchronized char charAt(int index) { 193 if ((index < 0) || (index >= count)) 194 throw new StringIndexOutOfBoundsException(index); 195 return value[index]; 196 } 197 198 /** 199 * @since 1.5 200 */ 201 @Override 202 public synchronized int codePointAt(int index) { 203 return super.codePointAt(index); 204 } 205 206 /** 207 * @since 1.5 208 */ 209 @Override 210 public synchronized int codePointBefore(int index) { 211 return super.codePointBefore(index); 212 } 213 214 /** 215 * @since 1.5 216 */ 217 @Override 218 public synchronized int codePointCount(int beginIndex, int endIndex) { 219 return super.codePointCount(beginIndex, endIndex); 220 } 221 222 /** 223 * @since 1.5 224 */ 225 @Override 226 public synchronized int offsetByCodePoints(int index, int codePointOffset) { 227 return super.offsetByCodePoints(index, codePointOffset); 228 } 229 230 /** 231 * @throws NullPointerException {@inheritDoc} 232 * @throws IndexOutOfBoundsException {@inheritDoc} 233 */ 234 @Override 235 public synchronized void getChars(int srcBegin, int srcEnd, char[] dst, 236 int dstBegin) 237 { 238 super.getChars(srcBegin, srcEnd, dst, dstBegin); 239 } 240 241 /** 242 * @throws IndexOutOfBoundsException {@inheritDoc} 243 * @see #length() 244 */ 245 @Override 246 public synchronized void setCharAt(int index, char ch) { 247 if ((index < 0) || (index >= count)) 248 throw new StringIndexOutOfBoundsException(index); 249 value[index] = ch; 250 } 251 252 @Override 253 public synchronized StringBuffer append(Object obj) { 254 super.append(String.valueOf(obj)); 255 return this; 256 } 257 258 @Override 259 public synchronized StringBuffer append(String str) { 260 super.append(str); 261 return this; 262 } 263 264 /** 265 * Appends the specified <tt>StringBuffer</tt> to this sequence. 266 * <p> 267 * The characters of the <tt>StringBuffer</tt> argument are appended, 268 * in order, to the contents of this <tt>StringBuffer</tt>, increasing the 269 * length of this <tt>StringBuffer</tt> by the length of the argument. 270 * If <tt>sb</tt> is <tt>null</tt>, then the four characters 271 * <tt>"null"</tt> are appended to this <tt>StringBuffer</tt>. 272 * <p> 273 * Let <i>n</i> be the length of the old character sequence, the one 274 * contained in the <tt>StringBuffer</tt> just prior to execution of the 275 * <tt>append</tt> method. Then the character at index <i>k</i> in 276 * the new character sequence is equal to the character at index <i>k</i> 277 * in the old character sequence, if <i>k</i> is less than <i>n</i>; 278 * otherwise, it is equal to the character at index <i>k-n</i> in the 279 * argument {@code sb}. 280 * <p> 281 * This method synchronizes on {@code this}, the destination 282 * object, but does not synchronize on the source ({@code sb}). 283 * 284 * @param sb the <tt>StringBuffer</tt> to append. 285 * @return a reference to this object. 286 * @since 1.4 287 */ 288 public synchronized StringBuffer append(StringBuffer sb) { 289 super.append(sb); 290 return this; 291 } 292 293 /** 294 * @since 1.8 295 */ 296 @Override 297 synchronized StringBuffer append(AbstractStringBuilder asb) { 298 super.append(asb); 299 return this; 300 } 301 302 /** 303 * Appends the specified {@code CharSequence} to this 304 * sequence. 305 * <p> 306 * The characters of the {@code CharSequence} argument are appended, 307 * in order, increasing the length of this sequence by the length of the 308 * argument. 309 * 310 * <p>The result of this method is exactly the same as if it were an 311 * invocation of this.append(s, 0, s.length()); 312 * 313 * <p>This method synchronizes on {@code this}, the destination 314 * object, but does not synchronize on the source ({@code s}). 315 * 316 * <p>If {@code s} is {@code null}, then the four characters 317 * {@code "null"} are appended. 318 * 319 * @param s the {@code CharSequence} to append. 320 * @return a reference to this object. 321 * @since 1.5 322 */ 323 @Override 324 public StringBuffer append(CharSequence s) { 325 // Note, synchronization achieved via invocations of other StringBuffer methods after 326 // narrowing of s to specific type 327 super.append(s); 328 return this; 329 } 330 331 /** 332 * @throws IndexOutOfBoundsException {@inheritDoc} 333 * @since 1.5 334 */ 335 @Override 336 public synchronized StringBuffer append(CharSequence s, int start, int end) 337 { 338 super.append(s, start, end); 339 return this; 340 } 341 342 @Override 343 public synchronized StringBuffer append(char[] str) { 344 super.append(str); 345 return this; 346 } 347 348 /** 349 * @throws IndexOutOfBoundsException {@inheritDoc} 350 */ 351 @Override 352 public synchronized StringBuffer append(char[] str, int offset, int len) { 353 super.append(str, offset, len); 354 return this; 355 } 356 357 @Override 358 public synchronized StringBuffer append(boolean b) { 359 super.append(b); 360 return this; 361 } 362 363 @Override 364 public synchronized StringBuffer append(char c) { 365 super.append(c); 366 return this; 367 } 368 369 @Override 370 public synchronized StringBuffer append(int i) { 371 super.append(i); 372 return this; 373 } 374 375 /** 376 * @since 1.5 377 */ 378 @Override 379 public synchronized StringBuffer appendCodePoint(int codePoint) { 380 super.appendCodePoint(codePoint); 381 return this; 382 } 383 384 @Override 385 public synchronized StringBuffer append(long lng) { 386 super.append(lng); 387 return this; 388 } 389 390 @Override 391 public synchronized StringBuffer append(float f) { 392 super.append(f); 393 return this; 394 } 395 396 @Override 397 public synchronized StringBuffer append(double d) { 398 super.append(d); 399 return this; 400 } 401 402 /** 403 * @throws StringIndexOutOfBoundsException {@inheritDoc} 404 * @since 1.2 405 */ 406 @Override 407 public synchronized StringBuffer delete(int start, int end) { 408 super.delete(start, end); 409 return this; 410 } 411 412 /** 413 * @throws StringIndexOutOfBoundsException {@inheritDoc} 414 * @since 1.2 415 */ 416 @Override 417 public synchronized StringBuffer deleteCharAt(int index) { 418 super.deleteCharAt(index); 419 return this; 420 } 421 422 /** 423 * @throws StringIndexOutOfBoundsException {@inheritDoc} 424 * @since 1.2 425 */ 426 @Override 427 public synchronized StringBuffer replace(int start, int end, String str) { 428 super.replace(start, end, str); 429 return this; 430 } 431 432 /** 433 * @throws StringIndexOutOfBoundsException {@inheritDoc} 434 * @since 1.2 435 */ 436 @Override 437 public synchronized String substring(int start) { 438 return substring(start, count); 439 } 440 441 /** 442 * @throws IndexOutOfBoundsException {@inheritDoc} 443 * @since 1.4 444 */ 445 @Override 446 public synchronized CharSequence subSequence(int start, int end) { 447 return super.substring(start, end); 448 } 449 450 /** 451 * @throws StringIndexOutOfBoundsException {@inheritDoc} 452 * @since 1.2 453 */ 454 @Override 455 public synchronized String substring(int start, int end) { 456 return super.substring(start, end); 457 } 458 459 /** 460 * @throws StringIndexOutOfBoundsException {@inheritDoc} 461 * @since 1.2 462 */ 463 @Override 464 public synchronized StringBuffer insert(int index, char[] str, int offset, 465 int len) 466 { 467 super.insert(index, str, offset, len); 468 return this; 469 } 470 471 /** 472 * @throws StringIndexOutOfBoundsException {@inheritDoc} 473 */ 474 @Override 475 public synchronized StringBuffer insert(int offset, Object obj) { 476 super.insert(offset, String.valueOf(obj)); 477 return this; 478 } 479 480 /** 481 * @throws StringIndexOutOfBoundsException {@inheritDoc} 482 */ 483 @Override 484 public synchronized StringBuffer insert(int offset, String str) { 485 super.insert(offset, str); 486 return this; 487 } 488 489 /** 490 * @throws StringIndexOutOfBoundsException {@inheritDoc} 491 */ 492 @Override 493 public synchronized StringBuffer insert(int offset, char[] str) { 494 super.insert(offset, str); 495 return this; 496 } 497 498 /** 499 * @throws IndexOutOfBoundsException {@inheritDoc} 500 * @since 1.5 501 */ 502 @Override 503 public StringBuffer insert(int dstOffset, CharSequence s) { 504 // Note, synchronization achieved via invocations of other StringBuffer methods 505 // after narrowing of s to specific type 506 super.insert(dstOffset, s); 507 return this; 508 } 509 510 /** 511 * @throws IndexOutOfBoundsException {@inheritDoc} 512 * @since 1.5 513 */ 514 @Override 515 public synchronized StringBuffer insert(int dstOffset, CharSequence s, 516 int start, int end) 517 { 518 super.insert(dstOffset, s, start, end); 519 return this; 520 } 521 522 /** 523 * @throws StringIndexOutOfBoundsException {@inheritDoc} 524 */ 525 @Override 526 public StringBuffer insert(int offset, boolean b) { 527 // Note, synchronization achieved via invocation of StringBuffer insert(int, String) 528 // after conversion of b to String by super class method 529 super.insert(offset, b); 530 return this; 531 } 532 533 /** 534 * @throws IndexOutOfBoundsException {@inheritDoc} 535 */ 536 @Override 537 public synchronized StringBuffer insert(int offset, char c) { 538 super.insert(offset, c); 539 return this; 540 } 541 542 /** 543 * @throws StringIndexOutOfBoundsException {@inheritDoc} 544 */ 545 @Override 546 public StringBuffer insert(int offset, int i) { 547 // Note, synchronization achieved via invocation of StringBuffer insert(int, String) 548 // after conversion of i to String by super class method 549 super.insert(offset, i); 550 return this; 551 } 552 553 /** 554 * @throws StringIndexOutOfBoundsException {@inheritDoc} 555 */ 556 @Override 557 public StringBuffer insert(int offset, long l) { 558 // Note, synchronization achieved via invocation of StringBuffer insert(int, String) 559 // after conversion of l to String by super class method 560 super.insert(offset, l); 561 return this; 562 } 563 564 /** 565 * @throws StringIndexOutOfBoundsException {@inheritDoc} 566 */ 567 @Override 568 public StringBuffer insert(int offset, float f) { 569 // Note, synchronization achieved via invocation of StringBuffer insert(int, String) 570 // after conversion of f to String by super class method 571 super.insert(offset, f); 572 return this; 573 } 574 575 /** 576 * @throws StringIndexOutOfBoundsException {@inheritDoc} 577 */ 578 @Override 579 public StringBuffer insert(int offset, double d) { 580 // Note, synchronization achieved via invocation of StringBuffer insert(int, String) 581 // after conversion of d to String by super class method 582 super.insert(offset, d); 583 return this; 584 } 585 586 /** 587 * @throws NullPointerException {@inheritDoc} 588 * @since 1.4 589 */ 590 @Override 591 public int indexOf(String str) { 592 // Note, synchronization achieved via invocations of other StringBuffer methods 593 return super.indexOf(str); 594 } 595 596 /** 597 * @throws NullPointerException {@inheritDoc} 598 * @since 1.4 599 */ 600 @Override 601 public synchronized int indexOf(String str, int fromIndex) { 602 return super.indexOf(str, fromIndex); 603 } 604 605 /** 606 * @throws NullPointerException {@inheritDoc} 607 * @since 1.4 608 */ 609 @Override 610 public int lastIndexOf(String str) { 611 // Note, synchronization achieved via invocations of other StringBuffer methods 612 return lastIndexOf(str, count); 613 } 614 615 /** 616 * @throws NullPointerException {@inheritDoc} 617 * @since 1.4 618 */ 619 @Override 620 public synchronized int lastIndexOf(String str, int fromIndex) { 621 return super.lastIndexOf(str, fromIndex); 622 } 623 624 /** 625 * @since JDK1.0.2 626 */ 627 @Override 628 public synchronized StringBuffer reverse() { 629 super.reverse(); 630 return this; 631 } 632 633 @Override 634 public synchronized String toString() { 635 return new String(value, 0, count); 636 } 637 638 /** 639 * Serializable fields for StringBuffer. 640 * 641 * @serialField value char[] 642 * The backing character array of this StringBuffer. 643 * @serialField count int 644 * The number of characters in this StringBuffer. 645 * @serialField shared boolean 646 * A flag indicating whether the backing array is shared. 647 * The value is ignored upon deserialization. 648 */ 649 private static final java.io.ObjectStreamField[] serialPersistentFields = 650 { 651 new java.io.ObjectStreamField("value", char[].class), 652 new java.io.ObjectStreamField("count", Integer.TYPE), 653 new java.io.ObjectStreamField("shared", Boolean.TYPE), 654 }; 655 656 /** 657 * readObject is called to restore the state of the StringBuffer from 658 * a stream. 659 */ 660 private synchronized void writeObject(java.io.ObjectOutputStream s) 661 throws java.io.IOException { 662 java.io.ObjectOutputStream.PutField fields = s.putFields(); 663 fields.put("value", value); 664 fields.put("count", count); 665 fields.put("shared", false); 666 s.writeFields(); 667 } 668 669 /** 670 * readObject is called to restore the state of the StringBuffer from 671 * a stream. 672 */ 673 private void readObject(java.io.ObjectInputStream s) 674 throws java.io.IOException, ClassNotFoundException { 675 java.io.ObjectInputStream.GetField fields = s.readFields(); 676 value = (char[])fields.get("value", null); 677 count = fields.get("count", 0); 678 } 679 }