jdk1.6的集合源碼閱讀之ArrayList

1. 簡述    

         ArrayList其實就是動態數組,是Array的複雜版本,動態擴容和縮容,靈活的設置數組的大小,等等。java

其定義以下編程

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

ArrayList繼承了AbstractList(這是一個抽象類,對一些基本的List操做進行了實現),實現了List。數組

ArrayList實現了RandmoAccess接口,即提供了隨機訪問功能。安全

ArrayList 實現了Cloneable接口,即覆蓋了函數clone(),能被克隆。多線程

ArrayList 實現java.io.Serializable接口,這意味着ArrayList支持序列化,能經過序列化去傳輸。app

和Vector不一樣, ArrayList中的操做不是線程安全的 !因此,建議在單線程中才使用ArrayList,而在多線程中能夠選擇Vector或者CopyOnWriteArrayList。dom

其繼承結構以下圖ide

藍色線條:繼承函數

綠色線條:接口實現測試

2.List接口

Iterable和Collection接口裏面聲明的方法咱們已經看過,如今看下List裏面的方法:

List基礎了Collection的全部方法,還本身聲明瞭一些針對List操做的獨有的方法

public interface List<E> extends Collection<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 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();
          //上面是繼承自Collection的方法,下面就是List本身獨有的方法
          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);
 }

而AbstractCollection實現了Collection的部分方法和AbstractList繼承了該AbstractCollection和實現了List部分方法,兩個的源碼就再也不這兒分析了,主角是ArrayList。

3.ArrayList的底層存儲

private transient Object[] elementData;


 private int size;

能夠看出,底層存儲是數組,仍是Object類型。elementData數組是使用transient修飾的,關於transient關鍵字的做用簡單說就是java自帶默認機制進行序列化的時候,被其修飾的屬性不須要維持, 簡單的理解就是:

java序列化的時候,帶有transient  修飾的屬性,不被序列化進去。

size是是用來記數的,表示容器的元素個數。爲何不用elementData.length來表示容器的個數呢?

答:由於數組的大小剛開始默認分配是10,可是若是隻存了5個對象,那麼,後面幾個爲null,沒有意義,因此須要使用size來記數,容器的元素到底有幾個。這就是這個設計的目的。

4.ArrayList的構造方法

它有三個構造方法,分別針對不一樣狀況下的初始化狀況,代碼以下;

//按照指定的容量進行初始化 
public ArrayList(int initialCapacity) {
	super();//調用父類的構造函數,父類的構造函數自己沒作什麼事情 
        if (initialCapacity < 0)  //檢查所傳入的參數的合法性
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
	this.elementData = new Object[initialCapacity];
}

    /**
  //默認初始化容量爲10
 public ArrayList() {
	this(10);
 }

   
//將一個容器來初始化成本身的容器元素 
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);
}

下面介紹其增刪改查

5.增長方法

//增長指定的元素到容器,在末尾
public boolean add(E e) {
    //檢查容量
	ensureCapacity(size + 1);  // Increments modCount!!
	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機器之後的元素拷貝到index+1的位置極其之後
	System.arraycopy(elementData, index, elementData, index + 1,
			 size - index);
	elementData[index] = element;
	size++; //容量加1
}

//增長一個集合的元素到ArrayList裏面去
public boolean addAll(Collection<? extends E> c) {
	Object[] a = c.toArray();
        int numNew = a.length;
	ensureCapacity(size + numNew);  // Increments modCount
        //將該內容拷貝容器的數組的後面
        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

	int numMoved = size - index;
	if (numMoved > 0)
        //先將該容器的index後面的元素拷貝到index+newNew以後,由於要留出位置拷貝要加入的內容
	    System.arraycopy(elementData, index, elementData, index + numNew,
			     numMoved);
        將c集合容器的內容拷貝到容器的index極其以後
        System.arraycopy(a, 0, elementData, index, numNew);
    //容器元素個數增長
	size += numNew;
	return numNew != 0;
 }

6.數組擴容

其實在每次增長以前,都進行檢查了,不夠就擴容

檢查並擴容的方法以下:

//數組容量檢查,不夠就進行擴容
//參數爲容器最小須要的容量(長度) 
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:
            //建立這個擴容後的長度的數組,沒有值的默認爲null
            elementData = Arrays.copyOf(elementData, newCapacity);
	}
}

7.刪除

//根據元素的位置刪除元素
public E remove(int index) {
    //檢查位置的範圍
	RangeCheck(index);

	modCount++;
    
	E oldValue = (E) elementData[index];

	int numMoved = size - index - 1;
	if (numMoved > 0)
        //將index後面的元素拷貝到index上面,長度爲後面的該移動的元素個數
	    System.arraycopy(elementData, index+1, elementData, index,
			     numMoved);
    //將最後一位數組元素置爲null,這樣垃圾回收機制就能夠回收了(作的很好),而後將size大小減一
	elementData[--size] = null; // Let gc do its work

    //返回老的元素
	return oldValue;
}

//刪除指定的元素  
public boolean remove(Object o) {
    //若是元素爲null
	if (o == null) {
            for (int index = 0; index < size; index++)
		if (elementData[index] == null) {
		    fastRemove(index);
		    return true;
		}
	} else {
	    for (int index = 0; index < size; index++)
		if (o.equals(elementData[index])) {
		    fastRemove(index);
		    return true;
		}
        }
	return false;
}

//能夠看出這個私有方法,只能它本身使用,根據位置,快速刪除 
private void fastRemove(int index) {
        modCount++;
        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);
}

//清空容量裏面的元素,並將大小置爲0
public void clear() {
	modCount++;

	// Let gc do its work
	for (int i = 0; i < size; i++)
	    elementData[i] = null;

	size = 0;
}

總結:能夠看出指定元素刪除和根據位置刪除方法比,速度要快不少,由於少了查找位置的循環。若是知道位置的話,咱們應該儘可能選擇根據元素的位置刪除。

8.縮容

        咱們知道,在添加元素的時候,咱們有可能會擴容,可是我刪除元素的時候,卻沒有縮容,雖然咱們將數組對應位置置爲null,其引用的對象會被gc回收,可是數組容量會愈來愈大了(這個操做類庫裏面只提供,本身基本沒有調用,應用程序應該 謹慎調用)。

//將數組的容量大小變爲實際的容器的元素個數那麼大
public void trimToSize() {
	modCount++;
	int oldCapacity = elementData.length;
	if (size < oldCapacity) {
            elementData = Arrays.copyOf(elementData, size);
	}
}

9.更新容器元素

//將指定位置的元素更改成指定的元素,並返回老的元素
public E set(int index, E element) {
	RangeCheck(index);

	E oldValue = (E) elementData[index];
	elementData[index] = element;
	return oldValue;
}

10.查找容器元素

//獲取指定位置的容器元素
 public E get(int index) {
    RangeCheck(index);

    return (E) elementData[index];
}


小結:增長和刪除的時候,咱們發現代碼寫的不少,並且用到了System.arraycopy來移動元素,效率極低,而查找和更新的時候,直接使用下標,很是簡單,效率極高。

11.其他的容器操做

11.1 查找元素是否在容器中

//判斷容器是否包含元素
public boolean contains(Object o) {
    //若是位置返回爲正,則包含
	return indexOf(o) >= 0;
}

//查看元素在容器中位置序號   
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]))//注意這兒是使用Object裏面的equal方法,因此是判斷兩個對象的引用是否是同一個對象。
		    return i;
	}
	return -1;
}

//返回元素在容器中最後一次的位置
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;
}

(o.equals(elementData[i]))

//注意這兒是使用Object裏面的equal方法,因此是判斷兩個對象的引用是否是同一個對象。若是不是爲-1

因此在下面有一個例子來講明

一個Recipe類

package it_cast.day01;

import java.util.LinkedList;
import java.util.List;

public class Recipe {
	private String name;
	private String key;
	private List<Recipe> childrenDepend;
	private Integer order;
	//private Recipe mRecipe;
	
	public List<Recipe> getChildrenDepend() {
		return childrenDepend;
	}

	public void setChildrenDepend(List<Recipe> childrenDepend) {
		this.childrenDepend = childrenDepend;
	}

	public Recipe() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	public Recipe(String name, String key) {
		super();
		this.name = name;
		this.key = key;
	}

	public Integer getOrder() {
		return order;
	}

	public void setOrder(Integer order) {
		this.order = order;
	}

	public Recipe(String name, String key,
			Integer order) {
		super();
		this.name = name;
		this.key = key;
		this.order = order;
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getKey() {
		return key;
	}
	public void setKey(String key) {
		this.key = key;
	}

	//@Override
	/*public String toString() {
		return "Recipe [name=" + name + ", key=" + key + "]";
	}*/
	
}

應用測試類

public class LinklistTestDemo2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		List <Recipe> a=new ArrayList<Recipe>();
		Recipe rec=new Recipe("keepalive服務","A");
		Recipe rec1=new Recipe("keepalive服務","B");
		Recipe rec2=new Recipe("keepalive服務","C");
		Recipe rec3=new Recipe("keepalive服務","D");
		Recipe rec4=new Recipe("keepalive服務","E");
		
		Recipe rec5=new Recipe("keepalive服務","E");
		a.add(rec);
		a.add(rec1);
		a.add(rec2);
		a.add(rec3);
		a.add(rec4);
		
		for(Recipe re:a){
			System.out.println("the app is:"+re.getKey());
			System.out.println(a.indexOf(re));
		}
		
		System.out.println(a.indexOf(rec5));
	}

}

打印結果

the app is:A
0
the app is:B
1
the app is:C
2
the app is:D
3
the app is:E
4
-1

注意:因爲rec5不是數組裏面引用的對象,只是值相等,因此找不到很正常,這兒編寫程序的人必定要注意了。

11.2 ArrayList轉爲數組

public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
}

public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
	System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
}

11.3克隆

public Object clone() {
	try {
	    ArrayList<E> v = (ArrayList<E>) super.clone();
	    v.elementData = Arrays.copyOf(elementData, size);
	    v.modCount = 0;
	    return v;
	} catch (CloneNotSupportedException e) {
	    // this shouldn't happen, since we are Cloneable
	    throw new InternalError();
	}
}

11.4序列化

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

}

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

打完收工,基本的差很少了

-------------------------------------------------------------------------------

後來看到好像有一個叫作FastArrayList的,剛開始還覺得比ArrayList要快不少,可是有篇文章說兩個測試效率差很少。

http://blog.csdn.net/feng27156/article/details/8504763

------------------------------------如下更新於2019年6月8號-------------------------

如今複習這塊知識以後,又有新的理解。

以前ArrayList的底層存儲裏面,使用了transient關鍵字,存儲這個數組,以下:

 private transient Object[] elementData;

當時在前面解釋了,可是當時並無真正的理解,因此當時也就是隨便解釋了一下,其實任何事物背後必有道理。咱們應該認真思考一下,爲何這個數組修飾符上面必定要加transient關鍵字呢?

1.  transient 關鍵字的做用是java對象在序列化的時候,被該關鍵字修飾的變量,不進行默認的序列化。

那咱們要思考,其實ArrayList這個實現了Serializable接口,表示能夠進行對象的序列化,可是不想對底層數組序列化,並且本身重寫了序列化和反序列化方法,以下:

private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
        // Write out element count, and any hidden stuff
        int expectedModCount = modCount;
        //調用默認的序列化的方法,將沒有transient 關鍵字的字段給序列化了
        s.defaultWriteObject();

        // Write out size as capacity for behavioural compatibility with clone()
        s.writeInt(size);

        // Write out all elements in the proper order.
        //序列化數組裏面的內容,由於這個內容被關鍵字transient修飾了,只能手動序列化了
        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 {
        elementData = EMPTY_ELEMENTDATA;

        // Read in size, and any hidden stuff
        s.defaultReadObject();

        // Read in capacity
        s.readInt(); // ignored

        if (size > 0) {
            // be like clone(), allocate array based upon size not capacity
            int capacity = calculateCapacity(elementData, size);
            SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, capacity);
            ensureCapacityInternal(size);

            Object[] a = elementData;
            // Read in all elements in the proper order.
            for (int i=0; i<size; i++) {
                a[i] = s.readObject();
            }
        }
    }

能夠看獲得本身序列化裏面,只序列化了,其真正存放的大小,而不是整個底層數組的內容,由於底層數組的大小通常都比實際的大小大不少,這些值,通常沒有值的時候,默認的是null, 沒有必要進行序列化。這個纔是主要目的。

若是對象方法裏面自動寫了writeObject和readObject的話,那麼對象序列化的時候,會調用這兩個方法進行序列化,而不是默認的,能夠在這兩個裏面調用defaultWriteObject和defaultReadObject進行默認的序列化。

這個能夠參考:java編程思想的序列化的章節

相關文章
相關標籤/搜索