java - 为什么 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);
}
...
}
解决方案
优化。如果我没记错的话,append 有两种实现。append(String)
比append(CharSequence)
where CharSequence
is a string 更有效。如果我必须做一些额外的例程来检查以确保CharSequence
与 String 兼容,将其转换为 String,然后运行 append(String),那将比直接 append(String) 更长。结果相同。速度不同。
推荐阅读
- xml - 在 XML 中使用 CDATA 作为参数
- mysql - AWS RDS 工作台连接问题
- vim - Vimscript - how can i check if a character is present in a variable
- reactjs - 当reducer在我的功能组件reactjs中出错时,我想清除或初始状态
- python - Pandas groupby 使用 MultiIndex 值
- typescript - 打字稿:使用 Object.assign 在构造函数中仅分配模型的现有属性
- here-api - HERE API 的月活跃用户数
- python - 在 scrapy 中使用 ItemLoader 将 KeyError 处理设置为默认值
- python-3.x - 如何用 Pandas 堆叠列
- c# - 替换文本文件中的文本