根据KathySierra的SCJP Study Guide:
当您需要修改字符串时,应使用java.lang.StringBuffer和java.lang.StringBuilder类。正如我们所讨论的那样,String对象是不可变的,因此如果您选择对String对象进行大量操作,则最终会在String池中留下许多放弃的String对象。
为了澄清这一点,我已经查看了String类和StringBuilder source here的代码。
String的简化代码如下:
我会尽力帮忙翻译。以下是需要翻译的内容:
如果我使用StringBuilder,代码将变为:
在StringBuilder中,
我的问题是:
使用简单的字符串连接和
根据上面列出的代码,
1.
当您需要修改字符串时,应使用java.lang.StringBuffer和java.lang.StringBuilder类。正如我们所讨论的那样,String对象是不可变的,因此如果您选择对String对象进行大量操作,则最终会在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 类:
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,代码将变为:
If I use StringBuilder, the code becomes:
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");
有同等的机会使持有字符串的字符数组被替换为新的字符数组。旧数组现在是无引用的,将被垃圾回收。我的问题是:
使用简单的字符串连接和
StringBuilder append()
方法,进入字符串池的String
对象数量相同。根据上面列出的代码,
StringBuilder
在首次使用更大的字符数组,而String
对象包含与其所持有的字符串长度相同的字符数组。1.
StringBuilder
比普通的String
类更有效地进行字符串操作的原因是什么?
2. SCJP Guide
中给出的陈述是否错误?
a
。但是如果我们在每次迭代中追加唯一的String
。比如第一个是 "a",然后是 "b",以此类推。那么s.append("a"); s.append("b");
将会在字符串池中创建a
、b
等字符串对象。我是正确的吗? - Aman Arora