为什么Java StringBuilder有一个用于CharSequence的构造函数,另一个用于String的构造函数?
2022-09-03 15:11:24
知道 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);
}
...
}