开发者

arraycopy(): Does Java ignore index arguments when length argument is 0?

I've written some code that I think should be failing under certain conditions, but it's not开发者_Go百科. I'm doing an arraycopy() which in some cases will ask for a copy to an out-of-bounds index, but in all such cases the length passed to arraycopy() would be 0.

My only guess is that Java's implementation of arraycopy() checks if length = 0 first, and if so returns without checking the index arguments? I can't find any reference to how the internals of arraycopy() work.

If this is the way Java implements it though, and the code works fine, my gut tells me that I should still write the code so this doesn't happen. Should I be worried about this?

The code is:

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++;
    }

Seems odd to me, but maybe I'm not thinking it through correctly? Should I just ensure capacity with manyItems >= data.length-1?


The indices are tested even if the length is 0. An index can be out of bounds if it is the length of the array, but anything larger triggers an ArrayIndexOutOfBoundsException.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜