Java Reference
In-Depth Information
One use for the
System.arraycopy
method is to add or remove elements in the
middle of an array. To add a new element at position
i
into data, first move all
elements from
i
onward one position up. Then insert the new value.
System.arraycopy(data, i, data, i + 1, data.length -
i - 1); data[i] = x;
Note that the last element in the array is lost (see
Figure 10
).
To remove the element at position
i
, copy the elements above the position downward
(see
Figure 11
).
System.arraycopy(data, i + 1, data, i, data.length -
i - 1);
312
313
Figure 10
Inserting a New Element into an Array