为什么 Java StringBuilder 有一个用于 CharSequence 的构造函数和另一个用于 String 的构造函数?
Why does Java StringBuilder have a constructor for CharSequence and another one for 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);
}
...
}
优化。如果我没记错的话,append 有两种实现方式。 append(String)
比 append(CharSequence)
更有效,其中 CharSequence
是一个字符串。如果我不得不做一些额外的例程来检查以确保 CharSequence
与字符串兼容,将其转换为字符串,然后 运行 追加(字符串),那将比追加(字符串)长直接地。同样的结果。不同的速度。
知道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);
}
...
}
优化。如果我没记错的话,append 有两种实现方式。 append(String)
比 append(CharSequence)
更有效,其中 CharSequence
是一个字符串。如果我不得不做一些额外的例程来检查以确保 CharSequence
与字符串兼容,将其转换为字符串,然后 运行 追加(字符串),那将比追加(字符串)长直接地。同样的结果。不同的速度。