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

Tre*_*ent 5 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++;
    }
Run Code Online (Sandbox Code Playgroud)

对我来说似乎很奇怪,但也许我没有正确考虑?我是否应该确保manyItems> = data.length-1的容量?

Ted*_*opp 3

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