问题
A sample of the statement to type when using the method is
System.arraycopy(data, i, data, i+1, data.length-i-1);
The way it works according to my book is that the system move all element from i
onward one position up. But intuitively I will think that the method will move all the element after i
one position down. So there is empty space to put the copied element.
I am confused now as to how to move elements around in the same array. What does the statement really say?
回答1:
The definition of System.arraycopy
is
System.arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length)
Therefore, this code copies
data[i .. (i + n - i - 1)] = data[i..(n-1)]
to
data[i+1 .. (i+1 + n-i-1)] = data[i+1..n]
(where the range includes the front but excludes the back, and n = data.length
)
and thus leaves a "blank" spot at data[i]
. Graphically:
[0] [1] [2] [3] ... [i] [i+1] [i+2] ... [n-2] [n-1]
src |-----------------------|
dest |-------------------------|
来源:https://stackoverflow.com/questions/27517893/how-does-the-system-arraycopy-method-work