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