gpt4 book ai didi

java - AbstractStringBuilder 类中的 expandCapacity 方法

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

我正在查看此类的源代码,我从 StringBUffer.append(); 调用的 append 方法开始

public AbstractStringBuilder append(String str) {
if (str == null) str = "null";
int len = str.length();
if (len == 0) return this;
int newCount = count + len;
if (newCount > value.length)
expandCapacity(newCount); // newcount is the new volumn of a char array
str.getChars(0, len, value, count);
count = newCount;
return this;
}

然后我深入研究了enpandCapacity方法

void expandCapacity(int minimumCapacity) {
int newCapacity = (value.length + 1) * 2; //here value is a char array
if (newCapacity < 0) { // Why is newCapacity less than 0?
// Is that possible? When it will be possible?
newCapacity = Integer.MAX_VALUE;
} else if (minimumCapacity > newCapacity) {
newCapacity = minimumCapacity;
}
value = Arrays.copyOf(value, newCapacity);
}

为什么 newCapacity 小于 0?那可能吗?什么时候可以?

最佳答案

是的;一旦超过 int 类型的最大值 (2^31 - 1),有符号整数可能会变为负数。如果您看一下,它们实际上是将容量限制在 Integer.MAX_VALUE。同类问题here .

关于java - AbstractStringBuilder 类中的 expandCapacity 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12273850/

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