2017-06-16 28 views
3

我正在學習Java StringBuilder的setLength methodJava StringBuilder setLength方法是否冗餘地爲其char []值數組賦值 0?

如果新的長度變長,它設置新「追加」數組的索引以「\ 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 language specification states。對於字符,這是'\ u0000',我知道它是'\ 0'的unicode等價物。

另外,StringBuilder setLength documentation狀態:

如果newLength參數大於或等於當前 長度,足夠空字符(「\ u0000的」)被附加使得 長度變newLength參數。

但這陣列的長度可以直接被訪問而不設定值到它的組成部分:

char[] array = new char[10]; 
System.out.println(array.length); // prints "10" 

所以,是for循環中setLength冗餘?

+0

for循環是追加\ 0s。 – 2017-06-16 02:44:04

+2

@JawadLeWywadi OP引用JLS的文檔表明這個附加是不必要的,因爲'\ 0'是'char'的默認值。 – 4castle

回答

1

這是需要當我們要重用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是不同的。