亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java中Vector與ArrayList的區(qū)別詳解

 更新時間:2013年06月04日 15:54:17   作者:  
本篇文章是對Java中Vector與ArrayList的區(qū)別進行了詳細的分析介紹,需要的朋友參考下
首先看這兩類都實現(xiàn)List接口,而List接口一共有三個實現(xiàn)類,分別是ArrayList、Vector和LinkedList。List用于存放多個元素,能夠維護元素的次序,并且允許元素的重復(fù)。
3個具體實現(xiàn)類的相關(guān)區(qū)別如下:

1.ArrayList是最常用的List實現(xiàn)類,內(nèi)部是通過數(shù)組實現(xiàn)的,它允許對元素進行快速隨機訪問。數(shù)組的缺點是每個元素之間不能有間隔,當數(shù)組大小不滿足時需要增加存儲能力,就要講已經(jīng)有數(shù)組的數(shù)據(jù)復(fù)制到新的存儲空間中。當從ArrayList的中間位置插入或者刪除元素時,需要對數(shù)組進行復(fù)制、移動、代價比較高。因此,它適合隨機查找和遍歷,不適合插入和刪除。

2.Vector與ArrayList一樣,也是通過數(shù)組實現(xiàn)的,不同的是它支持線程的同步,即某一時刻只有一個線程能夠?qū)慥ector,避免多線程同時寫而引起的不一致性,但實現(xiàn)同步需要很高的花費,因此,訪問它比訪問ArrayList慢。

3.LinkedList是用鏈表結(jié)構(gòu)存儲數(shù)據(jù)的,很適合數(shù)據(jù)的動態(tài)插入和刪除,隨機訪問和遍歷速度比較慢。另外,他還提供了List接口中沒有定義的方法,專門用于操作表頭和表尾元素,可以當作堆棧、隊列和雙向隊列使用。

查看Java源代碼,發(fā)現(xiàn)當數(shù)組的大小不夠的時候,需要重新建立數(shù)組,然后將元素拷貝到新的數(shù)組內(nèi),ArrayList和Vector的擴展數(shù)組的大小不同。
ArrayList中:
復(fù)制代碼 代碼如下:

public boolean add(E e) {
     ensureCapacity(size + 1);  // 增加元素,判斷是否能夠容納。不能的話就要新建數(shù)組
     elementData[size++] = e;
     return true;
 }
  public void ensureCapacity(int minCapacity) {
     modCount++;
     int oldCapacity = elementData.length;
     if (minCapacity > oldCapacity) {
         Object oldData[] = elementData; // 此行沒看出來用處,不知道開發(fā)者出于什么考慮
         int newCapacity = (oldCapacity * 3)/2 + 1; // 增加新的數(shù)組的大小
         if (newCapacity < minCapacity)
        newCapacity = minCapacity;
             // minCapacity is usually close to size, so this is a win:
             elementData = Arrays.copyOf(elementData, newCapacity);
     }
 }

Vector中:
復(fù)制代碼 代碼如下:

private void ensureCapacityHelper(int minCapacity) {
     int oldCapacity = elementData.length;
     if (minCapacity > oldCapacity) {
         Object[] oldData = elementData;
         int newCapacity = (capacityIncrement > 0) ?
        (oldCapacity + capacityIncrement) : (oldCapacity * 2);
         if (newCapacity < minCapacity) {
        newCapacity = minCapacity;
         }
        elementData = Arrays.copyOf(elementData, newCapacity);
     }
 }

關(guān)于ArrayList和Vector區(qū)別如下:
1.ArrayList在內(nèi)存不夠時默認是擴展50% + 1個,Vector是默認擴展1倍。
2.Vector提供indexOf(obj, start)接口,ArrayList沒有。
3.Vector屬于線程安全級別的,但是大多數(shù)情況下不使用Vector,因為線程安全需要更大的系統(tǒng)開銷。

相關(guān)文章

最新評論