Java中StringBuilder的构造方法
StringBuilder构造方法:
public StringBuilder(): 创建一个空白可变的字符串对象,不含有任何内容
public StringBuilder(): 根据字符串内容,来创建可变字符串对象
//链式编程
sb.append("hello").append("world").append("java").append(100);
System.out.println("sb".+sb);
//public StringBuilder reverse():返回相反的字符序列
sb.reverse();
System.out.println("sb:"+sb);
public static void main(String[] args) {
//public StringBuilder(): 创建一个空白可变的字符串对象,不含有任何内容
StringBuilder sb =new StringBuilder();
System.out.println("sb:"+sb);
System.out.println("sb.length()"+sb.length());
//public StringBuilder(): 根据字符串内容,来创建可变字符串对象
StringBuilder sb2 =new StringBuilder("hello");
System.out.println("sb2:"+sb);
System.out.println("sb2.length()"+sb2.length());
}
append() 方法
append(String str) 的操作如下:
- 判断 str 是否为空,若为空,则直接调用 appendNull() 并返回;
- 计算(count + len)追加 str 之后的长度,并确保存储字符序列的字符数组足够长;
- str.getChars() 方法将 str 复制到字符数组 value(存储了 StringBuffer 字符序列);
- 返回当前对象。
ensureCapacityInternal() 方法会检查字符数组 value 的容量是否足以存储追加之后的字符序列,不足则会进行扩容。count 表示 value 中下一个可用位置的下标
public AbstractStringBuilder append(String str) {
if (str == null)
return appendNull();
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
}