How does the System.arraycopy method work? [closed]

我们两清 提交于 2021-02-19 18:21:18

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!