arraycopy():当length参数为0时,Java是否忽略索引参数?

时间:2011-02-27 02:39:59

标签: java arrays arraycopy

我写了一些代码,我认为应该在某些条件下失败,但事实并非如此。我正在做一个arraycopy(),在某些情况下会要求复制到越界索引,但在所有这些情况下,传递给arraycopy()的长度都是0。

我唯一的猜测是Java的arraycopy()实现首先检查length = 0,如果是,则返回而不检查索引参数?我找不到有关arraycopy()内部工作方式的任何参考。

如果这是Java实现它的方式,并且代码工作正常,我的直觉告诉我,我仍然应该编写代码,这样就不会发生。我应该担心这个吗?

代码是:

if (manyItems == data.length) {
        ensureCapacity(manyItems * 2 + 1); 
    }
    if (manyItems == currentIndex) {
        data[currentIndex] = element;
    } 
    else {   // if data.length = 10, manyItems = 9, currentIndex = 8,
                     //   currentIndex + 2 = 10, which is out of bounds.
                     //   But manyItems - currentIndex -1 = 0, so nothing is copied.
        System.arraycopy(data, currentIndex + 1, data, currentIndex + 2,
            manyItems - currentIndex - 1);
        data[currentIndex + 1] = element;
        currentIndex++;
    }

对我来说似乎很奇怪,但也许我没有正确地思考它?我应该只使用manyItems> = data.length-1?

来确保容量

1 个答案:

答案 0 :(得分:2)

即使长度为0,也会测试索引。如果索引是数组的长度,则索引可以超出范围,但任何更大的索引都会触发ArrayIndexOutOfBoundsException。