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的对象。