gpt4 book ai didi

java - Java StringBuilder setLength 方法是否将\0 冗余分配给它的 char[] 值数组?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:50:08 25 4
gpt4 key购买 nike

我正在研究 Java StringBuilder 的 setLength method .

如果新的长度更大,它将新“追加”的数组索引设置为'\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 方法用于创建一个新的 char[] 数组,其大小为 newLength:

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数组中的组件被初始化为其默认值。对于 char,这是 '\u0000',据我所知,它是 '\0' 的 unicode 等价物。

另外,StringBuilder setLength documentation状态:

If the newLength argument is greater than or equal to the current length, sufficient null characters ('\u0000') are appended so that length becomes the newLength argument.

但是可以直接访问这个数组的长度,而无需为其组件赋值:

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的不一样

关于java - Java StringBuilder setLength 方法是否将\0 冗余分配给它的 char[] 值数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44579942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com