ArrayList源碼分析-面試必會(huì)

今天來說一說JAVA中我們比較熟悉的 ArrayList 解幼,據(jù)說在面試中要你手寫ArrayList都是有可能的论巍,所以我i這兩天讀了ArrayList的源碼,參考了一些資料,來把我的理解分享一下。

ArrayList 的特點(diǎn)

  1. ArrayList底層是基于Object[] 數(shù)組來實(shí)現(xiàn)的分预, 是一個(gè)動(dòng)態(tài)擴(kuò)展數(shù)組 ,Object數(shù)組默認(rèn)容量是10薪捍,當(dāng)長(zhǎng)度不夠時(shí)會(huì)自動(dòng)將容量擴(kuò)展到其原來的1.5倍笼痹。自動(dòng)增長(zhǎng)會(huì)帶來數(shù)據(jù)向新數(shù)組的拷貝配喳。

  2. ArrayList插入刪除操作都是通過數(shù)據(jù)在數(shù)組中的移動(dòng)實(shí)現(xiàn)的,所以增刪效率底凳干,而改查怎依然是通過數(shù)組下標(biāo)直接定位晴裹,改查效率高

  3. ArrayList線程不同步纺座,也就是線程不安全

  4. ArayList是有序的息拜,元素可重復(fù)的,允許元素為null

  5. ArrayList實(shí)現(xiàn)了Serializable接口净响,因此它支持序列化少欺,能夠通過序列化傳輸,實(shí)現(xiàn)了RandomAccess接口馋贤,支持快速隨機(jī)訪問赞别,實(shí)際上就是通過下標(biāo)序號(hào)進(jìn)行快速訪問,實(shí)現(xiàn)了Cloneable接口配乓,能被克隆仿滔。

源碼分析

下面進(jìn)行源碼分析,我知道有些小白看到源碼就會(huì)有懼怕感犹芹,但沒關(guān)系崎页,在我逐一講解的同時(shí)請(qǐng)你打開你的IDE進(jìn)入到ArrayList的源碼跟我一起看,你一定會(huì)感覺好多了腰埂。

一.屬性分析

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private static final long serialVersionUID = 8683452581122892189L;

    /**
     * Default initial capacity.
     * 默認(rèn)初始化容量為10
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.
     * 如果自定義容量為0飒焦,則會(huì)默認(rèn)用他倆初始化ArrayList,或者用于空數(shù)組替換
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * Shared empty array instance used for default sized empty instances. We
     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
     * first element is added.
     * 如果沒有定義容量則會(huì)用他來初始化ArrayList屿笼,或者用于空數(shù)組對(duì)比
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     *  這就是底層用到的數(shù)組牺荠,非私有,以簡(jiǎn)化嵌套類訪問
     *  transient 在已經(jīng)實(shí)現(xiàn)序列化的類中不允許某變量序列化
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     * 實(shí)際ArrayList集合的大小
     * @serial
     */
    private int size;

     /**
     * The maximum size of array to allocate.
     * Some VMs reserve some header words in an array.
     * Attempts to allocate larger arrays may result in
     * OutOfMemoryError: Requested array size exceeds VM limit
     * 可分配的最大容量
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

二.構(gòu)造方法分析

用無參構(gòu)造初始化驴一,默認(rèn)容量為10

public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

構(gòu)造一個(gè)初始容量為initialCapacity的空列表

如果傳入的initialCapacity為負(fù)數(shù)則會(huì)拋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);
        }
    }

通過結(jié)合做參數(shù)的形式初始化

按照集合的迭代返回他們的順序休雌,C集合的元素將被放入列表

如果集合為空則初始化為空數(shù)組

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

三.主方法解析

trimToSize()

用來最小化實(shí)例存儲(chǔ),將容器大小調(diào)整為當(dāng)前元素所占用的容量大小肝断,再底層的Copy方法實(shí)現(xiàn)了新數(shù)組的拷貝

/**
 * Trims the capacity of this <tt>ArrayList</tt> instance to be the
 * list's current size.  An application can use this operation to minimize
 * the storage of an <tt>ArrayList</tt> instance.
 */
public void trimToSize() {
    modCount++;
    if (size < elementData.length) {
        elementData = (size == 0)
          ? EMPTY_ELEMENTDATA
          : Arrays.copyOf(elementData, size);
    }
}
public static <T> T[] copyOf(T[] original, int newLength) {
    return (T[]) copyOf(original, newLength, original.getClass());
}
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
    @SuppressWarnings("unchecked")
    T[] copy = ((Object)newType == (Object)Object[].class)
        ? (T[]) new Object[newLength]
        : (T[]) Array.newInstance(newType.getComponentType(), newLength);
    System.arraycopy(original, 0, copy, 0,
                     Math.min(original.length, newLength));
    return copy;
}
public static Object newInstance(Class<?> componentType, int length)
    throws NegativeArraySizeException {
    return newArray(componentType, length);
}

clone()

克隆出一個(gè)新數(shù)組杈曲,通過調(diào)用Objectclone()方法來得到一個(gè)新的ArrayList對(duì)象,然后將elementData復(fù)制給該對(duì)象并返回胸懈。

/**
     * Returns a shallow copy of this <tt>ArrayList</tt> instance.  (The
     * elements themselves are not copied.)
     *
     * @return a clone of this <tt>ArrayList</tt> instance
     */
    public Object clone() {
        try {
            ArrayList<?> v = (ArrayList<?>) 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(e);
        }
    }

add(E e)

再數(shù)組添加元素

數(shù)據(jù)尾部插入鱼蝉,由于不會(huì)影響其他元素,因此會(huì)直接插入到后面箫荡。

public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

看到它首先調(diào)用了ensureCapacityInternal()方法.注意參數(shù)是size+1,這是個(gè)面試考點(diǎn)。

該方法做了兩件事:計(jì)算容量+確保容量

if語句進(jìn)行計(jì)算容量渔隶,如果elementData是空羔挡,則返回默認(rèn)容量10和size+1的最大值洁奈,否則返回size+1

private void ensureCapacityInternal(int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }

    ensureExplicitCapacity(minCapacity);
}

計(jì)算完容量后,進(jìn)行確保容量可用:(modCount不用理它绞灼,它用來計(jì)算修改次數(shù))

如果size+1 > elementData.length證明數(shù)組已經(jīng)放滿利术,則增加容量,調(diào)用grow()低矮。

private void ensureExplicitCapacity(int minCapacity) {
    modCount++;

    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

增加容量:默認(rèn)1.5倍擴(kuò)容印叁。

  1. 獲取當(dāng)前數(shù)組長(zhǎng)度=>oldCapacity

  2. oldCapacity>>1 表示將oldCapacity右移一位(位運(yùn)算),相當(dāng)于除2军掂。再加上1轮蜕,相當(dāng)于新容量擴(kuò)容1.5倍。

  3. 如果newCapacity>1=1,1<2所以如果不處理該情況蝗锥,擴(kuò)容將不能正確完成跃洛。

  4. 如果新容量比最大值還要大,則將新容量賦值為VM要求最大值终议。

  5. 將elementData拷貝到一個(gè)新的容量中汇竭。

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

add(int index, E element)

1.當(dāng)添加數(shù)據(jù)是在首位插入時(shí),先將新的數(shù)據(jù)放入到新的數(shù)組內(nèi)穴张,然后將原始數(shù)組中的數(shù)據(jù)復(fù)制到新的數(shù)組细燎。
2.當(dāng)數(shù)據(jù)插入的位置是中間位置時(shí),先將插入位置前面的數(shù)據(jù)先放到新的數(shù)組里皂甘,再放新的數(shù)據(jù)玻驻,再復(fù)制舊的數(shù)據(jù)完成添加。

3.數(shù)據(jù)尾部插入叮贩,由于不會(huì)影響其他元素击狮,因此會(huì)直接插入到后面。

public void add(int index, E element) {
    rangeCheckForAdd(index);

    ensureCapacityInternal(size + 1);  // Increments modCount!!
    System.arraycopy(elementData, index, elementData, index + 1,
                     size - index);
    elementData[index] = element;
    size++;
}

rangeCheckForAdd()是越界異常檢測(cè)方法益老。ensureCapacityInternal()之前有講彪蓬,著重說一下System.arrayCopy方法:

private void rangeCheckForAdd(int index) {
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
public static native void arraycopy(Object src,  int  srcPos,
                                    Object dest, int destPos,
                                    int length);

set(int index,E element)

覆蓋舊值并返回。

public E set(int index, E e) {
    rangeCheck(index);
    checkForComodification();
    E oldValue = ArrayList.this.elementData(offset + index);
    ArrayList.this.elementData[offset + index] = e;
    return oldValue;
}

異常檢查

private void rangeCheck(int index) {
    if (index < 0 || index >= this.size)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private void checkForComodification() {
    if (ArrayList.this.modCount != this.modCount)
        throw new ConcurrentModificationException();
}

獲取原值

E elementData(int index) {
        return (E) elementData[index];
    }

覆蓋

ArrayList.this.elementData[offset + index] = e;

indexOf(Object o)

比較簡(jiǎn)單 捺萌,根據(jù)Object對(duì)象獲取數(shù)組中的索引值档冬。

如果o為空,則返回?cái)?shù)組中第一個(gè)為空的索引桃纯;不為空也類似酷誓。

注意:通過源碼可以看到,該方法是允許傳空值進(jìn)來的态坦。

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

get(int index)

返回指定下標(biāo)處的元素的值盐数。

rangeCheck(index)會(huì)檢測(cè)index值是否合法,如果合法則返回索引對(duì)應(yīng)的值伞梯。

public E get(int index) {
    rangeCheck(index);

    return elementData(index);
}

remove(int index)

刪除指定下標(biāo)的元素玫氢。

1.從頭部刪除帚屉,刪除頭結(jié)點(diǎn)然后移動(dòng)后面的數(shù)據(jù),最后一個(gè)元素置空漾峡。
2.從中間指定位置刪除攻旦,找到要?jiǎng)h除數(shù)據(jù)的位置,刪除后生逸,后面的數(shù)據(jù)移動(dòng)牢屋,最后一個(gè)元素置空。

3.從尾部刪除:直接刪除尾部數(shù)據(jù)完成刪除操作槽袄。

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; // clear to let GC do its work

    return oldValue;
}

這么看下來其實(shí)ArrayList還不難烙无,而且也是比較基礎(chǔ)的東西,好好鉆研吧掰伸,加油皱炉!

我的博客:http://www.troubleq.com

https://segmentfault.com/u/troubleq

作者參考:源碼 + JAVA知音

網(wǎng)址:www.javazhiyin.com

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市狮鸭,隨后出現(xiàn)的幾起案子合搅,更是在濱河造成了極大的恐慌,老刑警劉巖歧蕉,帶你破解...
    沈念sama閱讀 219,270評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件灾部,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡惯退,警方通過查閱死者的電腦和手機(jī)赌髓,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來催跪,“玉大人锁蠕,你說我怎么就攤上這事“谜簦” “怎么了荣倾?”我有些...
    開封第一講書人閱讀 165,630評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)骑丸。 經(jīng)常有香客問我舌仍,道長(zhǎng),這世上最難降的妖魔是什么通危? 我笑而不...
    開封第一講書人閱讀 58,906評(píng)論 1 295
  • 正文 為了忘掉前任铸豁,我火速辦了婚禮,結(jié)果婚禮上菊碟,老公的妹妹穿的比我還像新娘节芥。我一直安慰自己,他們只是感情好逆害,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,928評(píng)論 6 392
  • 文/花漫 我一把揭開白布藏古。 她就那樣靜靜地躺著增炭,像睡著了一般。 火紅的嫁衣襯著肌膚如雪拧晕。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,718評(píng)論 1 305
  • 那天梅垄,我揣著相機(jī)與錄音厂捞,去河邊找鬼。 笑死队丝,一個(gè)胖子當(dāng)著我的面吹牛靡馁,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播机久,決...
    沈念sama閱讀 40,442評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼臭墨,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了膘盖?” 一聲冷哼從身側(cè)響起胧弛,我...
    開封第一講書人閱讀 39,345評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎侠畔,沒想到半個(gè)月后结缚,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,802評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡软棺,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,984評(píng)論 3 337
  • 正文 我和宋清朗相戀三年红竭,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片喘落。...
    茶點(diǎn)故事閱讀 40,117評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡茵宪,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出瘦棋,到底是詐尸還是另有隱情稀火,我是刑警寧澤,帶...
    沈念sama閱讀 35,810評(píng)論 5 346
  • 正文 年R本政府宣布兽狭,位于F島的核電站憾股,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏箕慧。R本人自食惡果不足惜服球,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,462評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望颠焦。 院中可真熱鬧斩熊,春花似錦、人聲如沸伐庭。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至霸株,卻和暖如春雕沉,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背去件。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評(píng)論 1 272
  • 我被黑心中介騙來泰國打工坡椒, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人尤溜。 一個(gè)月前我還...
    沈念sama閱讀 48,377評(píng)論 3 373
  • 正文 我出身青樓倔叼,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國和親宫莱。 傳聞我的和親對(duì)象是個(gè)殘疾皇子丈攒,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,060評(píng)論 2 355

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