1. 總體來說
java中主要的集合接口有Collection、Map上煤。Collection有一個(gè)父接口藏斩,Collection有三個(gè)子接口List、Set菇存、Queue夸研。
數(shù)據(jù)結(jié)構(gòu)灰常重要,所以依鸥,從架構(gòu)體系到代碼需要深入理解亥至。另外,會(huì)盜一些圖贱迟,哈哈姐扮。
java集合框架.png
2.List 接口的實(shí)現(xiàn)——ArrayList
ArrayList 是我們最常用的java數(shù)據(jù)結(jié)構(gòu)之一,通過學(xué)習(xí)其源碼衣吠,主要掌握其實(shí)現(xiàn)原理茶敏、擴(kuò)容機(jī)制以及一些主要方法的使用與實(shí)現(xiàn)。最后自己動(dòng)手實(shí)現(xiàn)一個(gè)簡單的ArrayList蒸播。
ArrayList.png
2.1 基本了解ArrayList
- ArrayList是基于數(shù)組實(shí)現(xiàn)的睡榆,是一個(gè)動(dòng)態(tài)數(shù)組萍肆,其容量能自動(dòng)增長,類似于C語言中的動(dòng)態(tài)申請內(nèi)存胀屿,動(dòng)態(tài)增長內(nèi)存塘揣。
- ArrayList不是線程安全的,只能用在單線程環(huán)境下宿崭,多線程環(huán)境下可以考慮用Collections.synchronizedList(List l)函數(shù)返回一個(gè)線程安全的ArrayList類亲铡,也可以使用concurrent并發(fā)包下的CopyOnWriteArrayList類。
- ArrayList實(shí)現(xiàn)了Serializable接口葡兑,因此它支持序列化奖蔓,能夠通過序列化傳輸,實(shí)現(xiàn)了RandomAccess接口讹堤,支持快速隨機(jī)訪問吆鹤,實(shí)際上就是通過下標(biāo)序號(hào)進(jìn)行快速訪問,實(shí)現(xiàn)了Cloneable接口洲守,能被克隆疑务。
- 每個(gè)ArrayList實(shí)例都有一個(gè)容量,該容量是指用來存儲(chǔ)列表元素的數(shù)組的大小梗醇。它總是至少等于列表的大小知允。隨著向ArrayList中不斷添加元素,其容量也自動(dòng)增長叙谨。自動(dòng)增長會(huì)帶來數(shù)據(jù)向新數(shù)組的重新拷貝温鸽,因此,如果可預(yù)知數(shù)據(jù)量的多少手负,可在構(gòu)造ArrayList時(shí)指定其容量涤垫。在添加大量元素前,應(yīng)用程序也可以使用ensureCapacity操作來增加ArrayList實(shí)例的容量虫溜,這可以減少遞增式再分配的數(shù)量雹姊。
2.2 源碼閱讀理解
- 屬性
// 默認(rèn)初始化容量為10
private static final int DEFAULT_CAPACITY = 10;
//一個(gè)空的對(duì)象數(shù)組用來存儲(chǔ)實(shí)例
private static final Object[] EMPTY_ELEMENTDATA = {};
//使用默認(rèn)構(gòu)造函數(shù)時(shí)
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//當(dāng)前數(shù)據(jù)對(duì)象,用transient 修飾衡楞,不參與序列化
transient Object[] elementData; // non-private to simplify nested class access
//當(dāng)前數(shù)組長度吱雏,并非容量
private int size;
//數(shù)組的最大長度
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
- 構(gòu)造方法
初始化帶容量的構(gòu)造器
/**
*初始化時(shí)帶容量如果大于0就new一個(gè)相應(yīng)大小的對(duì)象數(shù)組;容量等于
*0就調(diào)用預(yù)先定義好的空的對(duì)象數(shù)組瘾境;如果容量小于0則拋出 IllegalArgumentException
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
默認(rèn)構(gòu)造器歧杏,容量是10
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
帶Collention對(duì)象的構(gòu)造器
1.把Collention對(duì)象轉(zhuǎn)換成數(shù)組并且賦值給elementData,把數(shù)組的大小賦值給size
2.判斷是否為空數(shù)組如果是空數(shù)組則把預(yù)先聲明好的賦值給elementData;否則再做深拷貝
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
- 主要方法(先主后次)
add方法
有兩個(gè)迷守,add(E e)和add(int index, E element)
/**
*1)確保數(shù)組已使用長度(size)加1之后足夠存下 下一個(gè)數(shù)據(jù)
*2)修改次數(shù)modCount 標(biāo)識(shí)自增1犬绒,如果當(dāng)前數(shù)組已使用長度(size)加1后的大于當(dāng)前的數(shù)組長度,則調(diào)用grow方法兑凿,增長數(shù)組凯力,grow方法
*會(huì)將當(dāng)前數(shù)組的長度變?yōu)樵瓉砣萘康?.5倍茵瘾。
*3)確保新增的數(shù)據(jù)有地方存儲(chǔ)之后,則將新元素添加到位于size的位置上咐鹤。
*4)返回添加成功布爾值拗秘。
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
/**
* 在指定的位置插入元素
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
//檢查插入位置是否越界,如果index>size或則index<0 拋出IndexOutOfBoundsException異常
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
remove方法
一共涉及到四個(gè)方法分別是祈惶,E remove(int index) 雕旨、boolean remove(Object o)、 fastRemove(int index)捧请、clear() 凡涩。
/**
* 移除指定位置的元素
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
//邊界檢查
rangeCheck(index);
modCount++;
//需要移除的數(shù)據(jù)
E oldValue = elementData(index);
//計(jì)算需要移動(dòng)的數(shù)量
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//移除了一個(gè)元素,index后的元素都向前移動(dòng)了一位疹蛉,最后一個(gè)元素被孤立活箕,需要被GC回收,這點(diǎn)effective java 中也有說明
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
/**
* 遍歷元素氧吐,通過匹配值讹蘑,刪除指定的對(duì)象
* if it is present. If the list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists). Returns <tt>true</tt> if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*
* @param o element to be removed from this list, if present
* @return <tt>true</tt> if this list contained the specified element
*/
public boolean remove(Object o) {
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;
}
/*
* 實(shí)現(xiàn)快熟刪除末盔,原理是向前移動(dòng)數(shù)組筑舅,再把最后一個(gè)元素置空,讓GC回收
* return the value removed.
*/
private void fastRemove(int index) {
modCount++;
//需要移動(dòng)的元素個(gè)數(shù)
int numMoved = size - index - 1;
if (numMoved > 0)
//把index后的元素向前復(fù)制移動(dòng) System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}
/**
* 清空list陨舱,遍歷數(shù)組把每個(gè)元素置空翠拣,讓GC能夠回收
* be empty after this call returns.
*/
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}