Vector 学习笔记

Vector 是一种可增长的数组对象,类似于 ArrayList,它们都继承自 AbstractList 并实现了 List 接口。主要区别在于扩容策略:ArrayList 根据旧容量的50%扩容,而 Vector 按照 capacityIncrement 增长;此外,Vector 的所有操作方法都是同步的,适合多线程环境,但性能稍逊于 ArrayList。另外,Vector 没有 size 属性,使用 elementCount 记录元素数量,并提供 setSize 方法进行大小调整。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Vector 介绍

Vector实现了一种可增长的数组对象。它可以像数组一样,使用index访问元素。 Vector的大小可以根据需要增加或缩小,以适应Vector创建后添加和删除项目的需要。Vector 通过维护 capacity 和 capacityIncrement 来优化存储管理。capacity 的值大于等于Vector的size. Vector 创建后,Vector的存储量将以块( capacityIncrement那么多)的形式增加。

Vector 和 ArrayList的相同点

看代码:

public class Vector<E>
    extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
//省略
}
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
//省略
}

看到没有,他们继承了同一个父类ArrayList,实现了同样的接口 List, RandomAccess, Cloneable, java.io.Serializable。
那奇怪了,岂不是多余吗?不是的。往下看:

Vector 和 ArrayList的不同点

第一个不同点,就是他们扩容的方式。ArrayList扩容比较大气,根据当前的容量来。也就是:newCapacity = oldCapacity + (oldCapacity >> 1);

ArrayList的扩容方式:

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

而Vector比较抠门,每次只增加那么一点点。capacityIncrement 指定的那么多。
Vector的扩容方式:

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                         capacityIncrement : oldCapacity);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

那为什么Vector那么扣呢?我觉得是有原因的。Vector和ArrrayList都实现了List接口,Vector用关键字 synchronized 修饰了所有的 操作方法,以做到同步。 以remove()方法来说:

ArrayList的实现

    public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

看看Vector的实现,它在方法内调用的removeElement是使用了synchronized 修饰了的:

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

    public synchronized boolean removeElement(Object obj) {
        modCount++;
        int i = indexOf(obj);
        if (i >= 0) {
            removeElementAt(i);
            return true;
        }
        return false;
    

他们的size计算方式不一样
对应ArrayList.他会有个数组 elementData。 还会有一个属性 size。
在执行add方法的时候,如果成功,会对size进行加一操作。

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;

    /**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

但是对于Vector来时,就没有size这个属性了。它只有一个elementCount属性。它在添加一个元素的时候,先判断是否需要扩容,然后对 elementCount 执行加1操作。

    /**
     * Sets the size of this vector. If the new size is greater than the
     * current size, new {@code null} items are added to the end of
     * the vector. If the new size is less than the current size, all
     * components at index {@code newSize} and greater are discarded.
     *
     * @param  newSize   the new size of this vector
     * @throws ArrayIndexOutOfBoundsException if the new size is negative
     */
    public synchronized void setSize(int newSize) {
        modCount++;
        if (newSize > elementCount) {
            ensureCapacityHelper(newSize);
        } else {
            for (int i = newSize ; i < elementCount ; i++) {
                elementData[i] = null;
            }
        }
        elementCount = newSize;
    }
       
   /**
     * Adds the specified component to the end of this vector,
     * increasing its size by one. The capacity of this vector is
     * increased if its size becomes greater than its capacity.
     *
     * <p>This method is identical in functionality to the
     * {@link #add(Object) add(E)}
     * method (which is part of the {@link List} interface).
     *
     * @param   obj   the component to be added
     */
   public synchronized void addElement(E obj) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = obj;
    }

Vector 和 ArrayList相比,还多了一个setSize(int newSize) 操作。就是根据给定的siz大小,如果比现有的elementCount大,就去扩容,如果比现有的elementCount小,就以为着要搞清洗工作了,就是把超过的元素移出去啦。

    /**
     * Sets the size of this vector. If the new size is greater than the
     * current size, new {@code null} items are added to the end of
     * the vector. If the new size is less than the current size, all
     * components at index {@code newSize} and greater are discarded.
     *
     * @param  newSize   the new size of this vector
     * @throws ArrayIndexOutOfBoundsException if the new size is negative
     */
    public synchronized void setSize(int newSize) {
        modCount++;
        if (newSize > elementCount) {
            ensureCapacityHelper(newSize);
        } else {
            for (int i = newSize ; i < elementCount ; i++) {
                elementData[i] = null;
            }
        }
        elementCount = newSize;
    }

Vector还有cpacity()和size()方法,前者表示在不扩容的情况下,可以放多少对象进去。就是它持有对象数组的长度。
size()就是返回一个计数器elementCount.elementCount记录了到添加了多少个对象进去。

    /**
     * Returns the current capacity of this vector.
     *
     * @return  the current capacity (the length of its internal
     *          data array, kept in the field {@code elementData}
     *          of this vector)
     */
    public synchronized int capacity() {
        return elementData.length;
    }

    /**
     * Returns the number of components in this vector.
     *
     * @return  the number of components in this vector
     */
    public synchronized int size() {
        return elementCount;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值