1 /*
   2  * Copyright (c) 2003, 2018, 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 jdk.internal.HotSpotIntrinsicCandidate;
  29 
  30 /**
  31  * A mutable sequence of characters.  This class provides an API compatible
  32  * with {@code StringBuffer}, but with no guarantee of synchronization.
  33  * This class is designed for use as a drop-in replacement for
  34  * {@code StringBuffer} in places where the string buffer was being
  35  * used by a single thread (as is generally the case).   Where possible,
  36  * it is recommended that this class be used in preference to
  37  * {@code StringBuffer} as it will be faster under most implementations.
  38  *
  39  * <p>The principal operations on a {@code StringBuilder} are the
  40  * {@code append} and {@code insert} methods, which are
  41  * overloaded so as to accept data of any type. Each effectively
  42  * converts a given datum to a string and then appends or inserts the
  43  * characters of that string to the string builder. The
  44  * {@code append} method always adds these characters at the end
  45  * of the builder; the {@code insert} method adds the characters at
  46  * a specified point.
  47  * <p>
  48  * For example, if {@code z} refers to a string builder object
  49  * whose current contents are "{@code start}", then
  50  * the method call {@code z.append("le")} would cause the string
  51  * builder to contain "{@code startle}", whereas
  52  * {@code z.insert(4, "le")} would alter the string builder to
  53  * contain "{@code starlet}".
  54  * <p>
  55  * In general, if sb refers to an instance of a {@code StringBuilder},
  56  * then {@code sb.append(x)} has the same effect as
  57  * {@code sb.insert(sb.length(), x)}.
  58  * <p>
  59  * Every string builder has a capacity. As long as the length of the
  60  * character sequence contained in the string builder does not exceed
  61  * the capacity, it is not necessary to allocate a new internal
  62  * buffer. If the internal buffer overflows, it is automatically made larger.
  63  *
  64  * <p>Instances of {@code StringBuilder} are not safe for
  65  * use by multiple threads. If such synchronization is required then it is
  66  * recommended that {@link java.lang.StringBuffer} be used.
  67  *
  68  * <p>Unless otherwise noted, passing a {@code null} argument to a constructor
  69  * or method in this class will cause a {@link NullPointerException} to be
  70  * thrown.
  71  *
  72  * @apiNote
  73  * {@code StringBuilder} implements {@code Comparable} but does not override
  74  * {@link Object#equals equals}. Thus, the natural ordering of {@code StringBuilder}
  75  * is inconsistent with equals. Care should be exercised if {@code StringBuilder}
  76  * objects are used as keys in a {@code SortedMap} or elements in a {@code SortedSet}.
  77  * See {@link Comparable}, {@link java.util.SortedMap SortedMap}, or
  78  * {@link java.util.SortedSet SortedSet} for more information.
  79  *
  80  * @author      Michael McCloskey
  81  * @see         java.lang.StringBuffer
  82  * @see         java.lang.String
  83  * @since       1.5
  84  */
  85 public final class StringBuilder
  86     extends AbstractStringBuilder
  87     implements java.io.Serializable, Comparable<StringBuilder>, CharSequence
  88 {
  89 
  90     /** use serialVersionUID for interoperability */
  91     static final long serialVersionUID = 4383685877147921099L;
  92 
  93     /**
  94      * Constructs a string builder with no characters in it and an
  95      * initial capacity of 16 characters.
  96      */
  97     @HotSpotIntrinsicCandidate
  98     public StringBuilder() {
  99         super(16);
 100     }
 101 
 102     /**
 103      * Constructs a string builder with no characters in it and an
 104      * initial capacity specified by the {@code capacity} argument.
 105      *
 106      * @param      capacity  the initial capacity.
 107      * @throws     NegativeArraySizeException  if the {@code capacity}
 108      *               argument is less than {@code 0}.
 109      */
 110     @HotSpotIntrinsicCandidate
 111     public StringBuilder(int capacity) {
 112         super(capacity);
 113     }
 114 
 115     /**
 116      * Constructs a string builder initialized to the contents of the
 117      * specified string. The initial capacity of the string builder is
 118      * {@code 16} plus the length of the string argument.
 119      *
 120      * @param   str   the initial contents of the buffer.
 121      */
 122     @HotSpotIntrinsicCandidate
 123     public StringBuilder(String str) {
 124         super(str.length() + 16);
 125         append(str);
 126     }
 127 
 128     /**
 129      * Constructs a string builder that contains the same characters
 130      * as the specified {@code CharSequence}. The initial capacity of
 131      * the string builder is {@code 16} plus the length of the
 132      * {@code CharSequence} argument.
 133      *
 134      * @param      seq   the sequence to copy.
 135      */
 136     public StringBuilder(CharSequence seq) {
 137         this(seq.length() + 16);
 138         append(seq);
 139     }
 140 
 141     /**
 142      * Compares two {@code StringBuilder} instances lexicographically. This method
 143      * follows the same rules for lexicographical comparison as defined in the
 144      * {@linkplain java.lang.CharSequence#compare(java.lang.CharSequence,
 145      * java.lang.CharSequence)  CharSequence.compare(this, another)} method.
 146      *
 147      * <p>
 148      * For finer-grained, locale-sensitive String comparison, refer to
 149      * {@link java.text.Collator}.
 150      *
 151      * @param another the {@code StringBuilder} to be compared with
 152      *
 153      * @return  the value {@code 0} if this {@code StringBuilder} contains the same
 154      * character sequence as that of the argument {@code StringBuilder}; a negative integer
 155      * if this {@code StringBuilder} is lexicographically less than the
 156      * {@code StringBuilder} argument; or a positive integer if this {@code StringBuilder}
 157      * is lexicographically greater than the {@code StringBuilder} argument.
 158      *
 159      * @since 11
 160      */
 161     @Override
 162     public int compareTo(StringBuilder another) {
 163         return super.compareTo(another);
 164     }
 165 
 166     @Override
 167     public StringBuilder append(Object obj) {
 168         return append(String.valueOf(obj));
 169     }
 170 
 171     @Override
 172     @HotSpotIntrinsicCandidate
 173     public StringBuilder append(String str) {
 174         super.append(str);
 175         return this;
 176     }
 177 
 178     /**
 179      * Appends the specified {@code StringBuffer} to this sequence.
 180      * <p>
 181      * The characters of the {@code StringBuffer} argument are appended,
 182      * in order, to this sequence, increasing the
 183      * length of this sequence by the length of the argument.
 184      * If {@code sb} is {@code null}, then the four characters
 185      * {@code "null"} are appended to this sequence.
 186      * <p>
 187      * Let <i>n</i> be the length of this character sequence just prior to
 188      * execution of the {@code append} method. Then the character at index
 189      * <i>k</i> in the new character sequence is equal to the character at
 190      * index <i>k</i> in the old character sequence, if <i>k</i> is less than
 191      * <i>n</i>; otherwise, it is equal to the character at index <i>k-n</i>
 192      * in the argument {@code sb}.
 193      *
 194      * @param   sb   the {@code StringBuffer} to append.
 195      * @return  a reference to this object.
 196      */
 197     public StringBuilder append(StringBuffer sb) {
 198         super.append(sb);
 199         return this;
 200     }
 201 
 202     @Override
 203     public StringBuilder append(CharSequence s) {
 204         super.append(s);
 205         return this;
 206     }
 207 
 208     /**
 209      * @throws     IndexOutOfBoundsException {@inheritDoc}
 210      */
 211     @Override
 212     public StringBuilder append(CharSequence s, int start, int end) {
 213         super.append(s, start, end);
 214         return this;
 215     }
 216 
 217     @Override
 218     public StringBuilder append(char[] str) {
 219         super.append(str);
 220         return this;
 221     }
 222 
 223     /**
 224      * @throws IndexOutOfBoundsException {@inheritDoc}
 225      */
 226     @Override
 227     public StringBuilder append(char[] str, int offset, int len) {
 228         super.append(str, offset, len);
 229         return this;
 230     }
 231 
 232     @Override
 233     public StringBuilder append(boolean b) {
 234         super.append(b);
 235         return this;
 236     }
 237 
 238     @Override
 239     @HotSpotIntrinsicCandidate
 240     public StringBuilder append(char c) {
 241         super.append(c);
 242         return this;
 243     }
 244 
 245     @Override
 246     @HotSpotIntrinsicCandidate
 247     public StringBuilder append(int i) {
 248         super.append(i);
 249         return this;
 250     }
 251 
 252     @Override
 253     public StringBuilder append(long lng) {
 254         super.append(lng);
 255         return this;
 256     }
 257 
 258     @Override
 259     public StringBuilder append(float f) {
 260         super.append(f);
 261         return this;
 262     }
 263 
 264     @Override
 265     public StringBuilder append(double d) {
 266         super.append(d);
 267         return this;
 268     }
 269 
 270     /**
 271      * @since 1.5
 272      */
 273     @Override
 274     public StringBuilder appendCodePoint(int codePoint) {
 275         super.appendCodePoint(codePoint);
 276         return this;
 277     }
 278 
 279     /**
 280      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 281      */
 282     @Override
 283     public StringBuilder delete(int start, int end) {
 284         super.delete(start, end);
 285         return this;
 286     }
 287 
 288     /**
 289      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 290      */
 291     @Override
 292     public StringBuilder deleteCharAt(int index) {
 293         super.deleteCharAt(index);
 294         return this;
 295     }
 296 
 297     /**
 298      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 299      */
 300     @Override
 301     public StringBuilder replace(int start, int end, String str) {
 302         super.replace(start, end, str);
 303         return this;
 304     }
 305 
 306     /**
 307      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 308      */
 309     @Override
 310     public StringBuilder insert(int index, char[] str, int offset,
 311                                 int len)
 312     {
 313         super.insert(index, str, offset, len);
 314         return this;
 315     }
 316 
 317     /**
 318      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 319      */
 320     @Override
 321     public StringBuilder insert(int offset, Object obj) {
 322             super.insert(offset, obj);
 323             return this;
 324     }
 325 
 326     /**
 327      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 328      */
 329     @Override
 330     public StringBuilder insert(int offset, String str) {
 331         super.insert(offset, str);
 332         return this;
 333     }
 334 
 335     /**
 336      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 337      */
 338     @Override
 339     public StringBuilder insert(int offset, char[] str) {
 340         super.insert(offset, str);
 341         return this;
 342     }
 343 
 344     /**
 345      * @throws IndexOutOfBoundsException {@inheritDoc}
 346      */
 347     @Override
 348     public StringBuilder insert(int dstOffset, CharSequence s) {
 349             super.insert(dstOffset, s);
 350             return this;
 351     }
 352 
 353     /**
 354      * @throws IndexOutOfBoundsException {@inheritDoc}
 355      */
 356     @Override
 357     public StringBuilder insert(int dstOffset, CharSequence s,
 358                                 int start, int end)
 359     {
 360         super.insert(dstOffset, s, start, end);
 361         return this;
 362     }
 363 
 364     /**
 365      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 366      */
 367     @Override
 368     public StringBuilder insert(int offset, boolean b) {
 369         super.insert(offset, b);
 370         return this;
 371     }
 372 
 373     /**
 374      * @throws IndexOutOfBoundsException {@inheritDoc}
 375      */
 376     @Override
 377     public StringBuilder insert(int offset, char c) {
 378         super.insert(offset, c);
 379         return this;
 380     }
 381 
 382     /**
 383      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 384      */
 385     @Override
 386     public StringBuilder insert(int offset, int i) {
 387         super.insert(offset, i);
 388         return this;
 389     }
 390 
 391     /**
 392      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 393      */
 394     @Override
 395     public StringBuilder insert(int offset, long l) {
 396         super.insert(offset, l);
 397         return this;
 398     }
 399 
 400     /**
 401      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 402      */
 403     @Override
 404     public StringBuilder insert(int offset, float f) {
 405         super.insert(offset, f);
 406         return this;
 407     }
 408 
 409     /**
 410      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 411      */
 412     @Override
 413     public StringBuilder insert(int offset, double d) {
 414         super.insert(offset, d);
 415         return this;
 416     }
 417 
 418     @Override
 419     public int indexOf(String str) {
 420         return super.indexOf(str);
 421     }
 422 
 423     @Override
 424     public int indexOf(String str, int fromIndex) {
 425         return super.indexOf(str, fromIndex);
 426     }
 427 
 428     @Override
 429     public int lastIndexOf(String str) {
 430         return super.lastIndexOf(str);
 431     }
 432 
 433     @Override
 434     public int lastIndexOf(String str, int fromIndex) {
 435         return super.lastIndexOf(str, fromIndex);
 436     }
 437 
 438     @Override
 439     public StringBuilder reverse() {
 440         super.reverse();
 441         return this;
 442     }
 443 
 444     @Override
 445     @HotSpotIntrinsicCandidate
 446     public String toString() {
 447         // Create a copy, don't share the array
 448         return isLatin1() ? StringLatin1.newString(value, 0, count)
 449                           : StringUTF16.newString(value, 0, count);
 450     }
 451 
 452     /**
 453      * Save the state of the {@code StringBuilder} instance to a stream
 454      * (that is, serialize it).
 455      *
 456      * @serialData the number of characters currently stored in the string
 457      *             builder ({@code int}), followed by the characters in the
 458      *             string builder ({@code char[]}).   The length of the
 459      *             {@code char} array may be greater than the number of
 460      *             characters currently stored in the string builder, in which
 461      *             case extra characters are ignored.
 462      */
 463     private void writeObject(java.io.ObjectOutputStream s)
 464         throws java.io.IOException {
 465         s.defaultWriteObject();
 466         s.writeInt(count);
 467         char[] val = new char[capacity()];
 468         if (isLatin1()) {
 469             StringLatin1.getChars(value, 0, count, val, 0);
 470         } else {
 471             StringUTF16.getChars(value, 0, count, val, 0);
 472         }
 473         s.writeObject(val);
 474     }
 475 
 476     /**
 477      * readObject is called to restore the state of the StringBuffer from
 478      * a stream.
 479      */
 480     private void readObject(java.io.ObjectInputStream s)
 481         throws java.io.IOException, ClassNotFoundException {
 482         s.defaultReadObject();
 483         count = s.readInt();
 484         char[] val = (char[]) s.readObject();
 485         initBytes(val, 0, val.length);
 486     }
 487 
 488 }