Vector

它是ArrayList的线程安全版本,其实现90%和ArrayList都完全一样,区别在于:
1、Vector是线程安全的,ArrayList是线程非安全的,代码示例:
  public synchronized boolean add(E e) {
        modCount ++;
        ensureCapacityHelper( elementCount + 1);
        elementData [ elementCount ++] = e ;
        return true ;
    }

 public synchronized E remove(int index) {
        modCount ++;
        if ( index >= elementCount )
            throw new ArrayIndexOutOfBoundsException( index );
        E oldValue = elementData( index );
        int numMoved = elementCount - index - 1;
        if ( numMoved > 0)
            System. arraycopy ( elementData , index +1, elementData , index ,
                             numMoved );
        elementData [-- elementCount ] = null ; // Let gc do its work
        return oldValue ;
    }


2、Vector可以指定增长因子,如果该增长因子指定了,那么扩容的时候会每次新的数组大小会在原数组的大小基础上加上增长因子;如果不指定增长因子,那么就给原数组大小*2,源代码是这样的:
int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity);
capacityIncrement  变量是指定增长大小,默认为0,用户初始化时候可指定改变量大小
 public Vector() {
        this (10);
 }

 public Vector ( int initialCapacity ) {
        this ( initialCapacity , 0);
 }

  public Vector( int initialCapacity , int capacityIncrement ) {
        super ();
        if ( initialCapacity < 0)
            throw new IllegalArgumentException( "Illegal Capacity: " + initialCapacity );
        this . elementData = new Object[ initialCapacity ];
        this . capacityIncrement = capacityIncrement ;
  }

ArrayList源代码是这样的,在原来的基础上默认增长1.5倍:
 int newCapacity = oldCapacity + (oldCapacity >> 1);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值