ArrayList源碼分析

interface Iterable : //實(shí)現(xiàn)此接口使集合對(duì)象可以通過(guò)迭代器遍歷自身元素

? Iterator iterator();

public interface Collection extends Iterable: //接口繼承接口使用:extends

int size();

boolean isEmpty();

boolean contains(Object o);

boolean containsAll(Collection c);

boolean add(E e);

boolean addAll(Collection c);

boolean remove(Object o);

boolean removeAll(Collection c);

void clear();

boolean equals(Object o);

int hashCode();

boolean retainAll(Collection c);

Iterator iterator();

Object[] toArray();

T[] toArray(T[] a);

public interface List extends Collection

int size();

boolean isEmpty();

boolean contains(Object o);

Iterator iterator();

Object[] toArray();

T[] toArray(T[] a);

boolean add(E e);

boolean remove(Object o);

boolean removeAll(Collection c);

boolean containsAll(Collection c);

boolean addAll(Collection c);

boolean addAll(int index, 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 listIterator();

ListIterator listIterator(int index);

List subList(int fromIndex, int toIndex);

public class ArrayList extends AbstractList

implements List, RandomAccess, Cloneable, java.io.Serializable

private transient Object[] elementData;//實(shí)則為數(shù)組

? ? ? ? private int size;

public ArrayList() {//默認(rèn)長(zhǎng)度10

this(10);

}

public ArrayList(Collection c) {

elementData = c.toArray(); //現(xiàn)在elementData已經(jīng)可能不是Object[]

size = elementData.length;

// c.toArray might (incorrectly) not return Object[] (see 6260652)

if (elementData.getClass() != Object[].class)

//將另一個(gè)數(shù)組copy到當(dāng)前數(shù)組

? ? ? ? ? ? ? ? ? ? elementData = Arrays.copyOf(elementData, size, Object[].class);

}

public void trimToSize() {

modCount++;

int oldCapacity = elementData.length;//當(dāng)前長(zhǎng)度

? ? ? ? ? ? ? ? if (size < oldCapacity) {

//當(dāng)前數(shù)組長(zhǎng)度大于設(shè)定的size,將超過(guò)size部分的元素截掉

? ? ? ? ? ? ? ? ? ? elementData = Arrays.copyOf(elementData, size);

}

}

//數(shù)組擴(kuò)容/收縮[自我拷貝]

public static T[] copyOf(T[] original, int newLength) {

return (T[]) copyOf(original, newLength, original.getClass());

}

public boolean isEmpty() {

return size == 0;//是否為空板丽,即大小是否為0

}

public boolean contains(Object o) {

return indexOf(o) >= 0;//contains()底層調(diào)用的是indexOf()

}

public Object clone() {

try {

@SuppressWarnings("unchecked")

//淺克隆:只復(fù)制了基本類型字段

? ? ? ? ? ? ? ? ? ? ? ? ArrayList v = (ArrayList) super.clone();//???為什么克隆之后還要將內(nèi)容拷貝過(guò)去

? ? ? ? ? ? ? ? ? ? ? ? //深克陆娌怠:引用類型字段也復(fù)制

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

}

}

public Object[] toArray() {

return Arrays.copyOf(elementData, size);

}

public T[] toArray(T[] a) {

if (a.length < size) //小于elementData長(zhǎng)度時(shí)熔吗,通過(guò)Arrays.copyOf()復(fù)制出一個(gè)新的數(shù)組

? ? ? ? ? ? ? ? ? ? ? ? return (T[]) Arrays.copyOf(elementData, size, a.getClass());

System.arraycopy(elementData, 0, a, 0, size);

if (a.length > size)

a[size] = null;

return a;

}

//private:同類, default:同包, protected:不同包子類, public:公共

? ? ? ? ? ? E elementData(int index) {

return (E) elementData[index];

}

public E get(int index) {

rangeCheck(index); //throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

return elementData(index);

}

public E set(int index, E element) {

rangeCheck(index);

E oldValue = elementData(index);

elementData[index] = element;

return oldValue;

}

public boolean add(E e) {

ensureCapacityInternal(size + 1);? // Increments modCount!!

elementData[size++] = e;

return true;

}

private void ensureCapacityInternal(int minCapacity) {

modCount++;

// overflow-conscious code

if (minCapacity - elementData.length > 0)//elementData.length:這個(gè)不是數(shù)組實(shí)際長(zhǎng)度昧谊??

? ? ? ? ? ? ? ? ? ? ? ? grow(minCapacity);//超出容量,擴(kuò)容

? ? ? ? ? ? ? ? }

//防溢出

? ? ? ? ? ? private void grow(int minCapacity) {

// overflow-conscious code

int oldCapacity = elementData.length;

// >>位運(yùn)算国夜,右移動(dòng)一位。 整體相當(dāng)于newCapacity =oldCapacity + 0.5 * oldCapacity

// jdk1.7采用位運(yùn)算比以前的計(jì)算方式更快

? ? ? ? ? ? ? ? ? ? int newCapacity = oldCapacity + (oldCapacity >> 1);

if (newCapacity - minCapacity < 0) //這里為什么不直接用<【minCapacity可能為負(fù)數(shù)】

? ? ? ? ? ? ? ? ? ? ? ? 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);//自我拷貝

? ? ? ? ? ? ? ? }

public void add(int index, E element) {

rangeCheckForAdd(index);

ensureCapacityInternal(size + 1);? // Increments modCount!!

//將index之后的元素短绸,拷到index+1的位置之后

? ? ? ? ? ? ? ? ? ? System.arraycopy(elementData, index, elementData, index + 1,

size - index);

//空出index的位置车吹,將新元素加進(jìn)來(lái)

? ? ? ? ? ? ? ? ? ? elementData[index] = element;

size++;

}

public E remove(int index) {

rangeCheck(index);

modCount++;

E 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;

}

public boolean addAll(Collection c) {

Object[] a = c.toArray();

int numNew = a.length;

ensureCapacityInternal(size + numNew);? // Increments modCount

System.arraycopy(a, 0, elementData, size, numNew);//將新加的即可拷到原數(shù)組后面

? ? ? ? ? ? ? ? ? ? size += numNew;

return numNew != 0;

}

public boolean addAll(int index, Collection c) {

rangeCheckForAdd(index);

Object[] a = c.toArray();

int numNew = a.length;

ensureCapacityInternal(size + numNew);? // Increments modCount

int numMoved = size - index;

if (numMoved > 0)

System.arraycopy(elementData, index, elementData, index + numNew,

numMoved);

System.arraycopy(a, 0, elementData, index, numNew);

size += numNew;

return numNew != 0;

}

protected void removeRange(int fromIndex, int toIndex) {

modCount++;

int numMoved = size - toIndex;

System.arraycopy(elementData, toIndex, elementData, fromIndex,

numMoved);

// Let gc do its work

int newSize = size - (toIndex-fromIndex);

while (size != newSize)

elementData[--size] = null;

}

private class Itr implements Iterator {

int cursor;? ? ? // index of next element to return

int lastRet = -1; // index of last element returned; -1 if no such

//將arrayList被修改的次數(shù)記錄下來(lái),如果Itr遍歷過(guò)程中醋闭,modCount被修改窄驹,直接拋出異常

? ? ? ? ? ? ? ? ? ? ? ? int expectedModCount = modCount;

public void remove() {

if (lastRet < 0)

throw new IllegalStateException();

checkForComodification();

try {

/*靜態(tài)內(nèi)部類的話,只能new一個(gè)外部類對(duì)象了证逻。

若是實(shí)例內(nèi)部類乐埠,可以使用類名限定

例子:

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? (外部類類名)OuterClass.this就可以得到外部類的引用了。*/

ArrayList.this.remove(lastRet);

cursor = lastRet;

lastRet = -1;

//迭代器能過(guò)正常刪除元素的原因囚企,重置expectedModCount

expectedModCount = modCount;

} catch (IndexOutOfBoundsException ex) {

throw new ConcurrentModificationException();

}

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末丈咐,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子龙宏,更是在濱河造成了極大的恐慌棵逊,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,729評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件银酗,死亡現(xiàn)場(chǎng)離奇詭異辆影,居然都是意外死亡徒像,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,226評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門蛙讥,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)锯蛀,“玉大人,你說(shuō)我怎么就攤上這事键菱∶剑” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 169,461評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵经备,是天一觀的道長(zhǎng)拭抬。 經(jīng)常有香客問(wèn)我,道長(zhǎng)侵蒙,這世上最難降的妖魔是什么造虎? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 60,135評(píng)論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮纷闺,結(jié)果婚禮上算凿,老公的妹妹穿的比我還像新娘。我一直安慰自己犁功,他們只是感情好氓轰,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,130評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著浸卦,像睡著了一般署鸡。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上限嫌,一...
    開(kāi)封第一講書(shū)人閱讀 52,736評(píng)論 1 312
  • 那天靴庆,我揣著相機(jī)與錄音,去河邊找鬼怒医。 笑死炉抒,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的稚叹。 我是一名探鬼主播焰薄,決...
    沈念sama閱讀 41,179評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼扒袖!你這毒婦竟也來(lái)了塞茅?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 40,124評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤僚稿,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后蟀伸,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體蚀同,經(jīng)...
    沈念sama閱讀 46,657評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡缅刽,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,723評(píng)論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了蠢络。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片衰猛。...
    茶點(diǎn)故事閱讀 40,872評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖刹孔,靈堂內(nèi)的尸體忽然破棺而出啡省,到底是詐尸還是另有隱情,我是刑警寧澤髓霞,帶...
    沈念sama閱讀 36,533評(píng)論 5 351
  • 正文 年R本政府宣布卦睹,位于F島的核電站,受9級(jí)特大地震影響方库,放射性物質(zhì)發(fā)生泄漏结序。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,213評(píng)論 3 336
  • 文/蒙蒙 一纵潦、第九天 我趴在偏房一處隱蔽的房頂上張望徐鹤。 院中可真熱鬧,春花似錦邀层、人聲如沸返敬。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,700評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)劲赠。三九已至,卻和暖如春只磷,著一層夾襖步出監(jiān)牢的瞬間经磅,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,819評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工钮追, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留预厌,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,304評(píng)論 3 379
  • 正文 我出身青樓元媚,卻偏偏與公主長(zhǎng)得像轧叽,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子刊棕,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,876評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容