詳解Java中Vector和ArrayList的區別_java

來源:互聯網
上載者:User

首先看這兩類都實現List介面,而List介面一共有三個實作類別,分別是ArrayList、Vector和LinkedList。List用於存放多個元素,能夠維護元素的次序,並且允許元素的重複。

3個具體實作類別的相關區別如下:

1.ArrayList是最常用的List實作類別,內部是通過數組實現的,它允許對元素進行快速隨機訪問。數組的缺點是每個元素之間不能有間隔,當數組大小不滿足時需要增加儲存能力,就要講已經有數組的資料複製到新的儲存空間中。當從ArrayList的中間位置插入或者刪除元素時,需要對數組進行複製、移動、代價比較高。因此,它適合隨機尋找和遍曆,不適合插入和刪除。

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

3.LinkedList是用鏈表結構儲存資料的,很適合資料的動態插入和刪除,隨機訪問和遍曆速度比較慢。另外,他還提供了List介面中沒有定義的方法,專門用於動作表頭和表尾元素,可以當作堆棧、隊列和雙向隊列使用。

查看Java原始碼,發現當數組的大小不夠的時候,需要重建立立數組,然後將元素拷貝到新的數組內,ArrayList和Vector的擴充數組的大小不同。 

ArrayList中:

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

Vector中:

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); }}

關於ArrayList和Vector區別如下:

ArrayList在記憶體不夠時預設是擴充50% + 1個,Vector是預設擴充1倍。
Vector提供indexOf(obj, start)介面,ArrayList沒有。
Vector屬於安全執行緒層級的,但是大多數情況下不使用Vector,因為安全執行緒需要更大的系統開銷。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.