我正在查看此类的源代码,并从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?那可能吗?什么时候可能?
答案 0 :(得分:3)
是;一旦超过int类型的最大值( 2 ^ 31 - 1 ),有符号整数就会变为负数。如果你看一下,它们基本上限制了Integer.MAX_VALUE
的容量。类似问题here。