3

我正在查看这个类的源代码,我从被调用的 append 方法开始StringBUffer.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?那可能吗?什么时候可以?

4

1 回答 1

3

是的; 一旦超过 int 类型 ( 2^31 - 1 )的最大值,有符号整数就会变为负数。如果你看一下,他们基本上将容量限制在Integer.MAX_VALUE. 类似的问题在这里

于 2012-09-05T02:51:42.573 回答