首页 > 解决方案 > 为什么 Java StringBuilder 有一个用于 CharSequence 的构造函数和另一个用于 String 的构造函数?

问题描述

知道 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);
    }
...
}

标签: javastringbuilder

解决方案


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


推荐阅读