Vector数组类

    Vector工具类和ArrayList工具类都可以作为可变数组处理,只是Vector是线程安全,ArrayList线程非安全。下面详细介绍Vector类

    Vector类实现了List接口和继承了AbstractList类,所以Vector类有和ArrayList类相同的功能,包括添加add,删除remove,修改set(index, object),是否存在contain(object)等等。

    在Vector类中,有存储数据的elementData数组,记录数据大小的elementCount变量,数组自动增加量capacityIncrement变量。每一次添加数据都会存在elementData数组中,并且elementCount自增。在Vector中有些方法是同步的,比如添加元素:addElement(Object),将数组存到指定位置setElement(object,index)等。这些方法都是使用的synchronized修饰的同步方法。从ListAbstract类中继承的非同步方法,在Vector类中进行了重写。

    在Vector中,通过System.arraycopy()方法来复制数组,每一次删除或者修改Vector对象都会使用这个方法来复制数组,这是它的劣势,比如删除某一个元素:

public synchronized boolean removeElement(Object obj) {
    modCount++;
    int i = indexOf(obj);
    if (i >= 0) {
        removeElementAt(i);
        return true;
    }
    return false;
}
    首先通过indexOf()方法查到需要删除对象的index,然后调用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 */
}
    在上面的方法中,先通过elementCount判断index是否有效,有效的情况下调用System.arraycopy()方法复制元素(也就是填补index空缺的坑),最后将elementCount减1并把最后的对象索引指向null。

    Vector类中扩充数组容量也使用了Arrays.copyof(Object[] o, int length)方法,返回的数组length就是指定的length

    Vector对象add方法添加到数组elementCount位置,如果是调用add(E, index)这是需要移动数组,如果是set(E, index)则是覆盖原来index的对象。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值