【发布时间】:2013-12-24 03:09:22
【问题描述】:
根据 KathySierra 的 SCJP 学习指南:
java.lang.StringBuffer 和 java.lang.StringBuilder 类应该 当您必须对字符串进行修改时使用。 正如我们所讨论的,String 对象是不可变的,所以如果你选择这样做 对 String 对象进行大量操作,最终会得到很多 字符串池中废弃的字符串对象数
为了弄清楚这一点,我浏览了 String 类和 StringBuilder source here 的代码。
String 的简化代码如下所示:
public final class String(){
private final char [] value; //Final helps in immutability, I guess.
public String (String original){
value = original.value;
}
}
而StringBuilder的简化版是这样的:
public final class StringBuilder{
char [] value;
public StringBuilder(String str) {
value = new Char[(str.length() + 16)]; // 16 here is implementation dependent.
append(str);
}
public StringBuilder append(String str){
//Add 'str' characters in value array if its size allows,
else
// Create new array of size newCapacity and copy contents of 'value' in that.
//value = Arrays.copyOf(value, newCapacity);// here old array object is lost.
return this;
}
}
假设我们有一个案例如下:
使用字符串类:
String s1 = "abc"; // Creates one object on String pool.
s1 = s1+"def"; // Creates two objects - "def " on String pool
// and "abcdef" on the heap.
如果我使用StringBuilder,代码变成:
StringBuilder s1 = StringBuilder("abc");
// Creates one String object "abc " on String pool.
// And one StringBuilder object "abc" on the heap.
s1.append("def");
// Creates one string object "def" on String pool.
// And changes the char [] inside StringBuilder to hold "def" also.
在 StringBuilder s2 = s1.append("def"); 中,保存字符串的 char 数组将被新的 char 数组替换的机会相同。旧数组现在引用较少,将被垃圾回收。
我的查询是:
使用简单的字符串连接和StringBuilder append() 方法,进入字符串池的String 对象的数量是相同的。
根据上面列出的代码,StringBuilder 确实首先使用了更大的 char 数组,而 String 对象包含一个与它所保存的字符串长度相同的 char 数组。
-
StringBuilder的使用如何比平时更高效String用于字符串操作的类? -
SCJP Guide中的陈述是否有误?
【问题讨论】:
标签: java string stringbuilder