Java中Vector和ArrayList的區別

來源:互聯網
上載者:User

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

  1. ArrayList是最常用的List實作類別,內部是通過數組實現的,它允許對元素進行快速隨機訪問。數組的缺點是每個元素之間不能有間隔,當數組大小不滿足時需要增加儲存能力,就要講已經有數組的資料複製到新的儲存空間中。當從ArrayList的中間位置插入或者刪除元素時,需要對數組進行複製、移動、代價比較高。因此,它適合隨機尋找和遍曆,不適合插入和刪除。
  2. Vector與ArrayList一樣,也是通過數組實現的,不同的是它支援線程的同步,即某一時刻只有一個線程能夠寫Vector,避免多線程同時寫而引起的不一致性,但實現同步需要很高的花費,因此,訪問它比訪問ArrayList慢。
  3. LinkedList是用鏈表結構儲存資料的,很適合資料的動態插入和刪除,隨機訪問和遍曆速度比較慢。另外,他還提供了List介面中沒有定義的方法,專門用於動作表頭和表尾元素,可以當作堆棧、隊列和雙向隊列使用。

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

ArrayList中:

 1 public boolean add(E e) {
2
3 ensureCapacity(size + 1); // 增加元素,判斷是否能夠容納。不能的話就要建立數組
4  
5 elementData[size++] = e;
6
7 return true;
8
9 }
10
11  public void ensureCapacity(int minCapacity) {
12
13 modCount++;
14
15 int oldCapacity = elementData.length;
16
17 if (minCapacity > oldCapacity) {
18
19 Object oldData[] = elementData; // 此行沒看出來用處,不知道開發人員出於什麼考慮
20  
21 int newCapacity = (oldCapacity * 3)/2 + 1; // 增加新的數組的大小
22  
23 if (newCapacity < minCapacity)
24
25 newCapacity = minCapacity;
26
27 // minCapacity is usually close to size, so this is a win:
28  
29 elementData = Arrays.copyOf(elementData, newCapacity);
30
31 }
32
33 }
34
35  

 

 

Vector中:

 1 private void ensureCapacityHelper(int minCapacity) {
2
3 int oldCapacity = elementData.length;
4
5 if (minCapacity > oldCapacity) {
6
7 Object[] oldData = elementData;
8
9 int newCapacity = (capacityIncrement > 0) ?
10
11 (oldCapacity + capacityIncrement) : (oldCapacity * 2);
12
13 if (newCapacity < minCapacity) {
14
15 newCapacity = minCapacity;
16
17 }
18
19 elementData = Arrays.copyOf(elementData, newCapacity);
20
21 }
22
23 }
24
25

 

關於ArrayList和Vector區別如下:

  1. ArrayList在記憶體不夠時預設是擴充50% + 1個,Vector是預設擴充1倍。
  2. Vector提供indexOf(obj, start)介面,ArrayList沒有。
  3. 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.