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

标签 java stringbuilder

知道String实现了CharSequence接口(interface),那为什么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);
    }
...
}

最佳答案

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

关于java - 为什么 Java StringBuilder 有一个用于 CharSequence 的构造函数和另一个用于 String 的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56106628/

相关文章:

java - StringBuilder 和正则表达式解析

java - 如何在java中的字符串生成器中获取最后一个匹配项

java - LibGDX-libgdx 的意外计算

java - 如何在 Android Studio 上更改项目语言级别

java - 需要程序方面的帮助,FileInputStream 只读取文本文件的一行时遇到问题。 [作业帮助]

javascript - 如何将 GET 请求转换为 POST

python - 在 Python 中生成与 RegEx 匹配的字符串

java stringbuilder删除一行

java - 指定确切的 StringBuilder 容量还是使用默认值?

java - MongoDB Java 驱动程序 3.4+ 游标到数组