我是Java的新手,现在正在学习Java中的集合。让我感到困惑的是,我无法理解函数removeElementAt
如何工作当我阅读Vector
的源代码时
让我感到困惑的一点就是这个函数通过复制带有函数System.arraycopy
的剩余元素来删除元素,函数只是将源数组复制到指定长度限制的目标。如果我想删除那些元素坐在数组的中间?我假设它会丢弃那些位于spcified元素后面的元素,但它不像我想的那样工作。
功能removeElementAt
:
public synchronized void removeElementAt(int index) {
modCount++;
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
}
else if (index < 0) {
throw new ArrayIndexOutOfBoundsException(index);
}
int j = elementCount - index - 1;
if (j > 0) {
System.arraycopy(elementData, index + 1, elementData, index, j);
}
elementCount--;
elementData[elementCount] = null; /* to let gc do its work */
}
以下是我的测试代码:
/**
* Test if it will discard those element in the back
*/
public void TestRemoveElementAt(){
Vector<Integer> vector = new Vector<Integer>();
for(int i=0;i<10;i++){
vector.addElement(i);
}
// try to remove the number "7"
vector.removeElementAt(7);
// expected: 0 1 2 3 4 5 6
// actual: 0 1 2 3 4 5 6 8 9
vector.iterator().forEachRemaining(ele->System.out.print(ele+"\t"));
}
我的假设出了什么问题?
答案 0 :(得分:1)
让我们看一下System.arraycopy
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
来自System.arraycopy
从指定的源数组复制数组,从 指定的位置,到目标数组的指定位置。
如何调用
System.arraycopy(elementData, index + 1, elementData, index, j);
此处,来源和目的地相同(elementData
)
我们说从index + 1
开始( srcPos )并将长度j
的元素复制到从索引index
开始的同一个数组中( destPos )j = elementCount - index - 1;
因此,j
表示要删除index
后的元素数量。因此,这会在index
一个位置之后移动所有元素。