为什么Java StringBuilder有一个用于CharSequence的构造函数,另一个用于String的构造函数?

2022-09-03 15:11:24

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

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {...}
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);
    }
...
}

答案 1

优化。如果我没有记错的话,append 有两种实现。 比字符串更有效。如果我必须做一些额外的例程来检查以确保与String兼容,将其转换为String,然后运行append(String),这将比adph(String)直接长。同样的结果。不同的速度。append(String)append(CharSequence)CharSequenceCharSequence


答案 2

推荐