Java源碼解讀之util.ArrayList

來源:互聯網
上載者:User

ArrayList是List介面的一個可變長數組實現。實現了所有List介面的操作,並允許儲存null值。除了沒有進行同步,ArrayList基本等同於Vector。在Vector中幾乎對所有的方法都進行了同步,但ArrayList僅對writeObject和readObject進行了同步,其它比如add(Object)、remove(int)等都沒有同步。

1.儲存

ArrayList使用一個Object的數組儲存元素。

private transient Object elementData[];

ArrayList實現了java.io.Serializable介面,這兒的transient標示這個屬性不需要自動序列化。下面會在writeObject()方法中詳細講解為什麼要這樣作。

2.add和remove

public boolean add(Object o)
{
  ensureCapacity(size + 1);
  // Increments modCount!! elementData[size++] = o;
  return true;
}

注意這兒的ensureCapacity()方法,它的作用是保證elementData數組的長度可以容納一個新元素。在“自動變長機制”中將詳細講解。

public Object remove(int index)
{
  RangeCheck(index);
  modCount++;
  Object oldValue = elementData[index];
  int numMoved = size - index - 1;
  if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved);
  elementData[--size] = null; // Let gc do its work return oldValue;
}

RangeCheck()的作用是進行邊界檢查。由於ArrayList採用一個對象數組儲存元素,所以在刪除一個元素時需要把後面的元素前移。刪除一個元素時只是把該元素在elementData數組中的引用置為null,具體的對象的銷毀由垃圾收集器負責。

modCount的作用將在下面的“iterator()中的同步”中說明。

註:在前移時使用了System提供的一個實用方法:arraycopy(),在本例中可以看出System.arraycopy()方法可以對同一個數組進行操作,這個方法是一個native方法,如果對同一個數組進行操作時,會首先把從源部分拷貝到一個臨時數組,在把臨時數組的元素拷貝到目標位置。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.