ArrayList源码中的删除
/*
* Private remove method that skips bounds checking and does not
* return the value removed.
*/
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}
这一操作中的System.arraycopy目标数组和源数组都是同一个,因此并不需要额外的空间
public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
src:源数组;
srcPos:源数组要复制的起始位置;
dest:目的数组;
destPos:目的数组放置的起始位置;
length:复制的长度。
注意:src and dest都必须是同类型或者可以进行转换类型的数组.
public static void main(String[] args) {
String src[] = new String[] { "hello", "huang", "bao", "kang" };
String dest[] = new String[5];
System.arraycopy(src, 0, dest, 0, 4);
for (String str : dest) {
System.out.println(str);
}
System.out.println("=========华丽的分割线=========");
System.arraycopy(src, 0, src, 1, 3);
for (String str : src) {
System.out.println(str);
}
}
结果:
hello
huang
bao
kang
null
=========华丽的分割线=========
hello
hello
huang
bao