![](/img/trans.png)
[英]setLength() method is StringBuilder and how it works internally
[英]Does Java StringBuilder setLength method redundantly assign \0 to its char[] value array?
我正在研究Java StringBuilder的setLength方法 。
如果新長度較大,則將新“附加”數組索引設置為'\\ 0':
public void setLength(int newLength) {
if (newLength < 0)
throw new StringIndexOutOfBoundsException(newLength);
if (newLength > value.length)
expandCapacity(newLength);
if (count < newLength) {
for (; count < newLength; count++)
value[count] = '\0';
} else {
count = newLength;
}
}
這不必要嗎? 在expandCapacity(newLength)中,Arrays.copyOf方法用於創建一個大小為newLength的新char []數組:
public static char[] copyOf(char[] original, int newLength) {
char[] copy = new char[newLength];
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
Java語言規范聲明數組中的組件已初始化為其默認值。 對於char,這是'\\ u0000',我理解它是'\\ 0'的unicode等價物。
另外, StringBuilder setLength文檔說明:
如果newLength參數大於或等於當前長度,則會附加足夠的空字符('\\ u0000'),以便length成為newLength參數。
但是可以直接訪問此數組的長度,而無需為其組件賦值:
char[] array = new char[10];
System.out.println(array.length); // prints "10"
那么,setLength中的for循環是多余的嗎?
當我們想要重用StringBuilder
時,這是必要的 。
假設我們在StringBuilder
刪除此代碼
if (count < newLength) {
for (; count < newLength; count++)
value[count] = '\0';
}
我們用以下代碼測試:
StringBuilder builder = new StringBuilder("test");
builder.setLength(0); //the `value` still keeps "test", `count` is 0
System.out.println(builder.toString()); //print empty
builder.setLength(50); //side effect will happen here, "test" is not removed because expandCapacity still keeps the original value
System.out.println(builder.toString()); // will print test
您提到的代碼在jdk6中,在java8中是不同的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.