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

I wrote code that I think should work under certain conditions, but it is not. I am doing arraycopy (), which in some cases will request a copy of the index outside the limits, but in all such cases the length passed to arraycopy () will be 0.

My only assumption: Java implementation in arraycopy () checks if length = 0 is first, and if so returns without checking index arguments? I cannot find any reference to how the internal functions of arraycopy () work.

If this is how it implements Java, and the code works fine, my gut tells me that I should write code to prevent this from happening. Should I worry about this?

Code:

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

It seems strange to me, but maybe I don’t think it is right? Should I just provide capacity with manyItems> = data.length-1?

+4
source share
1 answer

Indexes are checked even if the length is 0. An index can be outside the bounds if it is the length of the array, but something larger causes an ArrayIndexOutOfBoundsException to fire.

+2
source

Source: https://habr.com/ru/post/1341483/


All Articles