給jdk寫註釋系列之jdk1.6容器(1):ArrayList源碼解析
工作中經常聽到別人講“容器”,各種各樣的容器,話說到底什麽是容器,通俗的講“容器就是用來裝東西的器皿,比如:水桶就是用來盛水的,水桶就是一個容器。”
ok,在我們寫程序的時候常常要對大量的對象進行管理,比如查詢,遍歷,修改等。jdk為我們提供的容器位於java.util包,也是我們平時用的最多的包之一。
但是為什麽不用數組(其實也不是不用,只是不直接用)呢,因為數組的長度需要提前確定,而且不能改變大小,用起來手腳受限嘛。
下面步入正題,首先我們想,一個對象管理容器需要哪些功能?增加,刪除,修改,查詢(crud對不對?)還有呢?遍歷,容量,是否包含某個元素。。。
功能是有了,如果讓你自己實現一個這樣的容器該怎麽實現呢?
我們看看ArrayList是怎麽實現這些功能的。
1.定義
首先先來看下頂級接口Collection的定義,
public interface Collection<E> extends Iterable<E> {
int size();
boolean isEmpty();
boolean contains(Object o);
Iterator<E> iterator();
Object[] toArray();
<T> T[] toArray(T[] a);
boolean add(E e);
boolean remove(Object o);
boolean containsAll(Collection<?> c);
boolean removeAll(Collection<?> c);
boolean retainAll(Collection<?> c);
void clear();
boolean equals(Object o);
int hashCode();
}
然後是接口List的定義,
public interface List<E> extends Collection<E> {
int size();
boolean isEmpty();
boolean contains(Object o);
Object[] toArray();
<T> T[] toArray(T[] a);
boolean add(E e);
boolean remove(Object o);
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c);
boolean addAll( int index, Collection<? extends E> c);
boolean removeAll(Collection<?> c);
boolean retainAll(Collection<?> c);
void clear();
boolean equals(Object o);
int hashCode();
E get( int index);
E set( int index, E element);
void add( int index, E element);
E remove( int index);
int indexOf(Object o);
int lastIndexOf(Object o);
ListIterator<E> listIterator();
ListIterator<E> listIterator( int index);
List<E> subList( int fromIndex, int toIndex);
}
再看下ArrayList的定義,
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
可以看出ArrayList繼承AbstractList(這是一個抽象類,對一些基礎的list操作進行封裝),實現List,RandomAccess,Cloneable,Serializable幾個接口,RandomAccess是一個標記接口,用來表明其支持快速隨機訪問。
2.底層存儲
顧名思義哈,ArrayList就是用數組實現的List容器,既然是用數組實現,當然底層用數組來保存數據啦。。。
private transient Object[] elementData;
private int size;
可以看到用一個Object數組來存儲數據,用一個int值來計數,記錄當前容器的數據大小。
另外,細心的人會發現elementData數組是使用transient修飾的,關於transient關鍵字的作用簡單說就是java自帶默認機制進行序列化的時候,被其修飾的屬性不需要維持。
會不會產生一點疑問?elementData不需要維持,那麽怎麽進行反序列化,又怎麽保證序列化和反序列化數據的正確性?難道不需要存儲?用大腿想一下那當然是不可以的嘛,既然需要存儲,它是怎麽實現的呢?註意上面紅色加粗的地方,默認序列化機制,嗯哼想明白了ArrayList一定是使用了自定義的序列化方式,到底是不是這樣的呢?看下面兩個方法:
/**
- Save the state of the <tt>ArrayList</tt> instance to a stream (that
- is, serialize it).
- @serialData The length of the array backing the <tt>ArrayList </tt>
- instance is emitted (int), followed by all of its elements
-
(each an <tt>Object</tt> ) in the proper order.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
// Write out element count, and any hidden stuff
int expectedModCount = modCount ;
s.defaultWriteObject();// Write out array length s.writeInt( elementData.length ); // Write out all elements in the proper order. for (int i=0; i<size; i++) s.writeObject( elementData[i]); if (modCount != expectedModCount) { throw new ConcurrentModificationException(); }
}
/**
- Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
-
deserialize it).
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in size, and any hidden stuff
s.defaultReadObject();// Read in array length and allocate array int arrayLength = s.readInt(); Object[] a = elementData = new Object[arrayLength]; // Read in all elements in the proper order. for (int i=0; i<size; i++) a[i] = s.readObject();
}
英語註釋很詳細,也很容易讀懂,就不進行翻譯了。那麽想一下為什麽要這樣設計呢,豈不是很麻煩。下面簡單進行解釋下:
elementData 是一個數據存儲數組,而數組是定長的,它會初始化一個容量,等容量不足時再擴充容量(擴容方式為數據拷貝,後面會詳細解釋),再通俗一點說就是比如elementData 的長度是10,而裏面只保存了3個對象,那麽數組中其余的7個元素(null)是沒有意義的,所以也就不需要保存,以節省序列化後的內存容量,好了到這裏就明白了這樣設計的初衷和好處,順便好像也明白了長度單獨用一個int變量保存,而不是直接使用elementData.length的原因。
3.構造方法
/**
-
構造一個具有指定容量的list
*/
public ArrayList( int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException( "Illegal Capacity: " +
initialCapacity);
this.elementData = new Object[initialCapacity];
}/**
-
構造一個初始容量為10的list
*/
public ArrayList() {
this(10);
}/**
- 構造一個包含指定元素的list,這些元素的是按照Collection的叠代器返回的順序排列的
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData .length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData .getClass() != Object[].class)
elementData = Arrays.copyOf( elementData, size , Object[].class);
}
構造方法看完了,想一下指定容量的構造方法的意義,既然默認為10就可以那麽為什麽還要提供一個可以指定容量大小的構造方法呢?在這裏說好像有點太早,那就賣個關子,下面再說。。。
4.增加
/**
-
添加一個元素
*/
public boolean add(E e) {
// 進行擴容檢查
ensureCapacity( size + 1); // Increments modCount
// 將e增加至list的數據尾部,容量+1
elementData[size ++] = e;
return true;
}/**
-
在指定位置添加一個元素
*/
public void add(int index, E element) {
// 判斷索引是否越界,這裏會拋出多麽熟悉的異常。。。
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: " +size);// 進行擴容檢查
ensureCapacity( size+1); // Increments modCount
// 對數組進行復制處理,目的就是空出index的位置插入element,並將index後的元素位移一個位置
System. arraycopy(elementData, index, elementData, index + 1,
size - index);
// 將指定的index位置賦值為element
elementData[index] = element;
// list容量+1
size++;
}
/** - 增加一個集合元素
*/
public boolean addAll(Collection<? extends E> c) {
//將c轉換為數組
Object[] a = c.toArray();
int numNew = a.length ;
//擴容檢查
ensureCapacity( size + numNew); // Increments modCount
//將c添加至list的數據尾部
System. arraycopy(a, 0, elementData, size, numNew);
//更新當前容器大小
size += numNew;
return numNew != 0;
}
/** -
在指定位置,增加一個集合元素
*/
public boolean addAll(int index, Collection<? extends E> c) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: " + index + ", Size: " + size);Object[] a = c.toArray();
int numNew = a.length ;
ensureCapacity( size + numNew); // Increments modCount// 計算需要移動的長度(index之後的元素個數)
int numMoved = size - index;
// 數組復制,空出第index到index+numNum的位置,即將數組index後的元素向右移動numNum個位置
if (numMoved > 0)
System. arraycopy(elementData, index, elementData, index + numNew,
numMoved);// 將要插入的集合元素復制到數組空出的位置中
System. arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}/**
- 數組容量檢查,不夠時則進行擴容
/
public void ensureCapacity( int minCapacity) {
modCount++;
// 當前數組的長度
int oldCapacity = elementData .length;
// 最小需要的容量大於當前數組的長度則進行擴容
if (minCapacity > oldCapacity) {
Object oldData[] = elementData;
// 新擴容的數組長度為舊容量的1.5倍+1
int newCapacity = (oldCapacity 3)/2 + 1;
// 如果新擴容的數組長度還是比最小需要的容量小,則以最小需要的容量為長度進行擴容
if (newCapacity < minCapacity)
newCapacity = minCapacity;
// minCapacity is usually close to size, so this is a win:
// 進行數據拷貝,Arrays.copyOf底層實現是System.arrayCopy()
elementData = Arrays.copyOf( elementData, newCapacity);
}
}
5.刪除
/**
-
根據索引位置刪除元素
*/
public E remove( int index) {
// 數組越界檢查
RangeCheck(index);modCount++;
// 取出要刪除位置的元素,供返回使用
E oldValue = (E) elementData[index];
// 計算數組要復制的數量
int numMoved = size - index - 1;
// 數組復制,就是將index之後的元素往前移動一個位置
if (numMoved > 0)
System. arraycopy(elementData, index+1, elementData, index,
numMoved);
// 將數組最後一個元素置空(因為刪除了一個元素,然後index後面的元素都向前移動了,所以最後一個就沒用了),好讓gc盡快回收
// 不要忘了size減一
elementData[--size ] = null; // Let gc do its workreturn oldValue;
}
/**
-
根據元素內容刪除,只刪除匹配的第一個
*/
public boolean remove(Object o) {
// 對要刪除的元素進行null判斷
// 對數據元素進行遍歷查找,知道找到第一個要刪除的元素,刪除後進行返回,如果要刪除的元素正好是最後一個那就慘了,時間復雜度可達O(n) 。。。
if (o == null) {
for (int index = 0; index < size; index++)
// null值要用==比較
if (elementData [index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
// 非null當然是用equals比較了
if (o.equals(elementData [index])) {
fastRemove(index);
return true;
}
}
return false;
}/*
- Private remove method that skips bounds checking and does not
-
return the value removed.
*/
private void fastRemove(int index) {
modCount++;
// 原理和之前的add一樣,還是進行數組復制,將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
}/**
- 數組越界檢查
*/
private void RangeCheck(int index) {
if (index >= size )
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: " +size);
}
PS:看到了這個方法,便可jdk源碼有些地方寫的也不是那麽精巧,比如這裏remove時將數組越界檢查封裝成了一個單獨方法,可是往前翻一下add方法中的數組越界就沒有進行封裝,需要檢查的時候都是寫一遍一樣的代碼,why啊。。。
增加和刪除方法到這裏就解釋完了,代碼是很簡單,主要需要特別關心的就兩個地方:1.數組擴容,2.數組復制,這兩個操作都是極費效率的,最慘的情況下(添加到list第一個位置,刪除list最後一個元素或刪除list第一個索引位置的元素)時間復雜度可達O(n)。
還記得上面那個坑嗎(為什麽提供一個可以指定容量大小的構造方法 )?看到這裏是不是有點明白了呢,簡單解釋下:如果數組初試容量過小,假設默認的10個大小,而我們使用ArrayList的主要操作時增加元素,不斷的增加,一直增加,不停的增加,會出現上面後果?那就是數組容量不斷的受挑釁,數組需要不斷的進行擴容,擴容的過程就是數組拷貝System.arraycopy的過程,每一次擴容就會開辟一塊新的內存空間和數據的復制移動,這樣勢必對性能造成影響。那麽在這種以寫為主(寫會擴容,刪不會縮容)場景下,提前預知性的設置一個大容量,便可減少擴容的次數,提高了性能。
需要註意的是,數組擴容伴隨著開辟新建的內存空間以創建新數組然後進行數據復制,而數組復制不需要開辟新內存空間,只需將數據進行復制。
上面講增加元素可能會進行擴容,而刪除元素卻不會進行縮容,如果在已刪除為主的場景下使用list,一直不停的刪除而很少進行增加,那麽會出現什麽情況?再或者數組進行一次大擴容後,我們後續只使用了幾個空間,會出現上面情況?當然是空間浪費啦啦啦,怎麽辦呢?
/**
- 將底層數組的容量調整為當前實際元素的大小,來釋放空間。
*/
public void trimToSize() {
modCount++;
// 當前數組的容量
int oldCapacity = elementData .length;
// 如果當前實際元素大小 小於 當前數組的容量,則進行縮容
if (size < oldCapacity) {
elementData = Arrays.copyOf( elementData, size );
}
6.更新
/** -
將指定位置的元素更新為新元素
*/
public E set( int index, E element) {
// 數組越界檢查
RangeCheck(index);// 取出要更新位置的元素,供返回使用
E oldValue = (E) elementData[index];
// 將該位置賦值為行的元素
elementData[index] = element;
// 返回舊元素
return oldValue;
}
7.查找
/**
-
查找指定位置上的元素
*/
public E get( int index) {
RangeCheck(index);return (E) elementData [index];
}
由於ArrayList使用數組實現,更新和查找直接基於下標操作,變得十分簡單。
8.是否包含
/**
- Returns <tt>true</tt> if this list contains the specified element.
- More formally, returns <tt>true</tt> if and only if this list contains
- at least one element <tt>e</tt> such that
- <tt>(o==null ? e==null : o.equals(e))</tt>.
- @param o element whose presence in this list is to be tested
-
@return <tt> true</tt> if this list contains the specified element
*/
public boolean contains(Object o) {
return indexOf(o) >= 0;
}/**
- Returns the index of the first occurrence of the specified element
- in this list, or -1 if this list does not contain the element.
- More formally, returns the lowest index <tt>i</tt> such that
- <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
-
or -1 if there is no such index.
*/
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData [i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData [i]))
return i;
}
return -1;
}/**
- Returns the index of the last occurrence of the specified element
- in this list, or -1 if this list does not contain the element.
- More formally, returns the highest index <tt>i</tt> such that
- <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
- or -1 if there is no such index.
*/
public int lastIndexOf(Object o) {
if (o == null) {
for (int i = size-1; i >= 0; i--)
if (elementData [i]==null)
return i;
} else {
for (int i = size-1; i >= 0; i--)
if (o.equals(elementData [i]))
return i;
}
return -1;
}
contains主要是檢查indexOf,也就是元素在list中出現的索引位置也就是數組下標,再看indexOf和lastIndexOf代碼是不是很熟悉,沒錯,和public booleanremove(Object o) 的代碼一樣,都是元素null判斷,都是循環比較,不多說了。。。但是要知道,最差的情況(要找的元素是最後一個)也是很慘的。。。
9.容量判斷
/** - Returns the number of elements in this list.
-
@return the number of elements in this list
*/
public int size() {
return size ;
}/**
- Returns <tt>true</tt> if this list contains no elements.
- @return <tt> true</tt> if this list contains no elements
*/
public boolean isEmpty() {
return size == 0;
}
由於使用了size進行計數,發現list大小獲取和判斷真的好容易。。。總結:
好了,至此ArrayList的分析和註釋就基本完成了。什麽還差些什麽?對,modCount 是幹什麽的,怎麽到處都在操作這個變量,還有遍歷呢,為啥不講?由於iterator遍歷相對比較復雜,而且iterator 是GoF經典設計模式比較重要的一個,之後會對iterator單獨分析,這裏就不啰嗦了。。。
給jdk寫註釋系列之jdk1.6容器(1):ArrayList源碼解析