知道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/