为什么Java StringBuilder具有CharSequence的构造函数和String的构造函数?

Abd*_*ane 15 java stringbuilder

知道String实现了CharSequence接口,那么为什么StringBuilder有一个CharSequence的构造函数和另一个String的构造函数?javadoc中没有指示!

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {...}
Run Code Online (Sandbox Code Playgroud)
public final class StringBuilder
    extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence
{

...

    /**
     * Constructs a string builder initialized to the contents of the
     * specified string. The initial capacity of the string builder is
     * {@code 16} plus the length of the string argument.
     *
     * @param   str   the initial contents of the buffer.
     */
    public StringBuilder(String str) {
        super(str.length() + 16);
        append(str);
    }

    /**
     * Constructs a string builder that contains the same characters
     * as the specified {@code CharSequence}. The initial capacity of
     * the string builder is {@code 16} plus the length of the
     * {@code CharSequence} argument.
     *
     * @param      seq   the sequence to copy.
     */
    public StringBuilder(CharSequence seq) {
        this(seq.length() + 16);
        append(seq);
    }
...
}
Run Code Online (Sandbox Code Playgroud)

Geo*_*ier 13

优化。如果我没记错的话,有两种实现append的方法。append(String)append(CharSequence)在哪里更有效CharSequence。如果我必须执行一些额外的例程来检查,以确保CharSequence它与String兼容,将其转换为String,然后运行append(String),那将比直接append(String)长。结果相同。不同的速度。

  • “ StringBuilder通常用于字符串,因此名称”`StringBuilder`用于构建* String。它的名字并没有说明它期望它们是从...构建的。 (14认同)
  • @AndyTurner的确类似于,如果您拥有一些“ CarBuilder”,则不必*接受*汽车。它需要汽车*零件*。如果它确实接受Car对象,则可能会重新使用其零件。 (2认同)
  • 此处的特定优化是String提供了一种getChars方法,该方法利用System.arraycopy将字符从字符串的内部char数组直接复制到StringBuilders的char数组中。天真的CharSequence版本必须遍历每个索引调用charAt的序列。 (2认同)