java+vector+remove_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 */

}

整个流程分析:

6e2bfafa52aca4bc639ad4e3c7e84b14.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值