Java向量'removeElementAt'函数实际上是如何工作的?

Java向量'removeElementAt'函数实际上是如何工作的?,java,vector,collections,Java,Vector,Collections,我是Java新手,现在正在学习Java中的集合。让我感到困惑的是,当我阅读Vector的源代码时,我无法理解函数removeementat是如何工作的 让我困惑的是,这个函数通过使用函数System.arraycopy,复制那些剩余的元素来删除元素,它只是将源数组复制到指定长度内的目标。如果我要删除位于数组中间的那些元素,该怎么办?我假设它会丢弃位于指定元素后面的那些元素,但它的工作方式与我所想的不同 功能删除组件: public synchronized void removeElementA

我是Java新手,现在正在学习Java中的集合。让我感到困惑的是,当我阅读
Vector
的源代码时,我无法理解函数
removeementat
是如何工作的

让我困惑的是,这个函数通过使用函数
System.arraycopy
,复制那些剩余的元素来删除元素,它只是将源数组复制到指定长度内的目标。如果我要删除位于数组中间的那些元素,该怎么办?我假设它会丢弃位于指定元素后面的那些元素,但它的工作方式与我所想的不同

功能
删除组件

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 */
    }
public synchronized void removeElementAt(int索引){
modCount++;
如果(索引>=元素计数){
抛出新的ArrayIndexOutOfBoundsException(索引+“>=”+
元素计数);
}
else if(索引<0){
将新的ArrayIndex抛出BoundsException(索引);
}
int j=元素计数-索引-1;
如果(j>0){
System.arraycopy(elementData,索引+1,elementData,索引,j);
}
元素计数--;
elementData[elementCount]=null;/*以让gc完成其工作*/
}
下面是我的测试代码:

   /**
     * 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"));
    }
/**
*测试它是否会丢弃后面的元素
*/
公共无效TestRemoveElementAt(){
向量=新向量();
对于(int i=0;iSystem.out.print(ele+“\t”);
}

我的假设有什么问题?

让我们看看
系统的方法签名。arraycopy

public static native void arraycopy(Object src,  int  srcPos,
                                    Object dest, int destPos,
                                    int length);
来自
System.arraycopy的javadoc

从指定的源阵列复制阵列,从 指定位置,到目标阵列的指定位置

它叫什么

System.arraycopy(elementData, index + 1, elementData, index, j);
这里,源和目标是相同的(
elementData

我们说从
index+1
(srcPos)开始,将长度
j
的元素复制到相同的数组,从index
index
(destPos)开始,其中
j=elementCount-index-1


因此,
j
将表示要删除的
索引之后的元素数。因此,这会将
索引之后的所有元素向下移动一个位置。

如果您是从头开始学习,我建议避免使用已过时多年的类,例如Vector。请看ArrayList。谢谢你,我会采纳你的建议。但我只是想找出我的假设是错误的原因?也许我是一个顽固的程序员,哈哈!!我好像找到了钥匙!正因为它是从
index+1
开始的复制操作,这意味着
index
的内存空间将被覆盖得太多,所以我的问题是我误解了复制的含义。你从
index+1开始复制所有内容(按顺序)从
index
开始编写它们,我同意你的观点!!