Abd*_*ane 15 java stringbuilder
知道String实现了CharSequence接口,那么为什么StringBuilder有一个CharSequence的构造函数和另一个String的构造函数?javadoc中没有指示!
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {...}
Run Code Online (Sandbox Code Playgroud)
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);
}
...
}
Run Code Online (Sandbox Code Playgroud)
Geo*_*ier 13
优化。如果我没记错的话,有两种实现append的方法。append(String)比append(CharSequence)在哪里更有效CharSequence。如果我必须执行一些额外的例程来检查,以确保CharSequence它与String兼容,将其转换为String,然后运行append(String),那将比直接append(String)长。结果相同。不同的速度。
| 归档时间: |
|
| 查看次数: |
1201 次 |
| 最近记录: |