[英]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.