Vector与ArrayList区别

  一、Vector与ArrayList区别

  1、ArrayList是最常用的List实现类,内部是通过数组实现的,它允许对元素进行快速随机访问。数组的缺点是每个元素之间不能有间隔,当数组大小不满足时需要增加存储能力,就要将已经有数组的数据复制到新的存储空间中。当从ArrayList的中间位置插入或者删除元素时,需要对数组进行复制、移动、代价比较高。因此,它适合随机查找和遍历,不适合插入和删除。

  2、Vector与ArrayList一样,也是通过数组实现的,不同的是它支持线程的同步,即某一时刻只有一个线程能够写Vector,避免多线程同时写而引起的不一致性,但实现同步需要很高的花费,因此,访问它比访问ArrayList慢。

  注意:Vector线程安全、ArrayList线程非安全

  3、Vector的源码中可以看到,new Vector()一个空的Vector的时候,其大小为10,容量的增量是0。同时不管是add和get方法都有synchronized关键字进行线程加锁。

1  /**
2      * Constructs an empty vector so that its internal data array
3      * has size {@code 10} and its standard capacity increment is
4      * zero.
5      */
6     public Vector() {
7         this(10);
8     }
1  public synchronized boolean add(E e) {
2         modCount++;
3         ensureCapacityHelper(elementCount + 1);
4         elementData[elementCount++] = e;
5         return true;
6     }
1 public synchronized E get(int index) {
2         if (index >= elementCount) //下表大于或等于元素的个数数组越界
3             throw new ArrayIndexOutOfBoundsException(index);
4 
5         return elementData(index);
6     }

  ArrayList的源码默认的初始容量大小是10,其中add和get方法中都没有加synchronized关键字,故是线程非安全,执行效率更高,但是不能保证数据一致性。

 1 /**
 2      * Default initial capacity.
 3      */
 4     private static final int DEFAULT_CAPACITY = 10;
 5 /**
 6      * Constructs an empty list with an initial capacity of ten.
 7      */
 8     public ArrayList() {
 9         this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
10     }
 1  /**
 2      * Appends the specified element to the end of this list.
 3      *
 4      * @param e element to be appended to this list
 5      * @return <tt>true</tt> (as specified by {@link Collection#add})
 6      */
 7     public boolean add(E e) {
 8         ensureCapacityInternal(size + 1);  // Increments modCount!!
 9         elementData[size++] = e;
10         return true;
11     }
 1   /**
 2      * Returns the element at the specified position in this list.
 3      *
 4      * @param  index index of the element to return
 5      * @return the element at the specified position in this list
 6      * @throws IndexOutOfBoundsException {@inheritDoc}
 7      */
 8     public E get(int index) {
 9         rangeCheck(index);
10 
11         return elementData(index);
12     }

 

 

  

posted @ 2019-09-19 20:54  houstao  阅读(380)  评论(0编辑  收藏  举报