java.util.包中Vector类remove(Object o)方法的源码分析

 remove(Object o)方法的源代码:

public boolean remove(Object o) {
    return removeElement(o);
}

 removeElement(Object obj)方法的源代码:

public synchronized boolean removeElement(Object obj) {
    modCount++;//这个参数是什么先暂时不做考虑
    int i = indexOf(obj);
    if (i >= 0) {
        removeElementAt(i);
        return true;
    }
    return false;
}

indexOf(Object o)方法的源代码:

public int indexOf(Object o) {
    return indexOf(o, 0);
}

 indexOf(Object o, int index)方法的源代码:

public synchronized int indexOf(Object o, int index) {
        if (o == null) {
            for (int i = index ; i < elementCount ; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = index ; i < elementCount ; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

removeElement(int index)方法的源代码:

public synchronized void removeElementAt(int index) {
        modCount++;
//分析里面已经对index的范围有了说明,index并没有小于0或者>=elementCount(元素数量),所以目前博主不知道为什么源代码中还要有这样一个if 和 else if去判断其是否在这两个范围内,欢迎留言
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                                     elementCount);
        }
        else if (index < 0) {
            throw new ArrayIndexOutOfBoundsException(index);
        }
        int j = elementCount - index - 1;
        if (j > 0) {//j>0时说明所要删除的数据不是数组的最后一位(自己可以画图验证,便于理解)
            System.arraycopy(elementData, index + 1, elementData, index, j);//将要删除的地方之后的数据提前一位
        }
        elementCount--;//元素总量减一
        elementData[elementCount] = null; /* to let gc do its work */
    }

整个流程分析:

猜你喜欢

转载自blog.csdn.net/My_name_is_ZwZ/article/details/82751307