ArraryList源碼分析

ArrayList 是一個最簡單的線性存儲的支持隨機訪問的數(shù)據(jù)結(jié)構(gòu), 線程不安全, 不適合大數(shù)據(jù)的存儲杯活,如果要達(dá)到性能最佳慎冤,最好事先知道存儲大小鸥拧。

構(gòu)造函數(shù)

//指定容量绢彤,創(chuàng)建數(shù)組
    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);
        }
    }

//指定數(shù)據(jù)對象創(chuàng)建ArrayList
    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

    //添加數(shù)據(jù)操作
    public boolean add(E e) {
        //先執(zhí)行擴(kuò)容
        ensureCapacityInternal(size + 1); // Increments modCount!!
        //添加數(shù)據(jù)
        elementData[size++] = e;
        return true;
    }
    
    //確認(rèn)新的容量是否符合梯啤, 返回符合的容量
    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }

    //使用指定容量擴(kuò)容
    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    } 
    
    //擴(kuò)容操作
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    
    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:
        //這個東西在復(fù)制類的時候只能復(fù)制引用
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

addAll

    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);  // Increments modCount

        int numMoved = size - index;
        
        //復(fù)制原始數(shù)組尾部谴垫,到新數(shù)據(jù)尾部
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);
        
        //復(fù)制新數(shù)據(jù)到數(shù)組中
        
        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }

get

    public E get(int index) {
        //檢查下標(biāo)是否符合
        rangeCheck(index);
        return elementData(index);
    }
    
    //獲取數(shù)據(jù)章母,主要還是進(jìn)行類型的轉(zhuǎn)換
    E elementData(int index) {
        return (E) elementData[index];
    }

remove

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

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

        int numMoved = size - index - 1;
        //移動數(shù)據(jù)
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        //設(shè)置為null, GC
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }
    
    
    public boolean remove(Object o) {
        if (o == null) {
        //如果為空,則清除空的對象翩剪,直接判斷是否為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;
    }
    
    //這一步胳施,和get是一樣的
    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; // clear to let GC do its work
    }
    
    //清空數(shù)據(jù),實際上不會使得容量發(fā)生變化
    public void clear() {
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }

contains

    //實際上是遍歷數(shù)組
    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]))
                    return i;
        }
        return -1;
    }

Iterator

    //返回一個迭代器實例肢专, 迭代器為內(nèi)部類舞肆,持有ArrayList 實例引用
    public Iterator<E> iterator() {
        return new Itr();
    }
    
        private class Itr implements Iterator<E> {
        int cursor;       // 游標(biāo)
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        Itr() {}

        public boolean hasNext() {
            return cursor != size;
        }

        //獲取一個元素
        @SuppressWarnings("unchecked")
        public E next() {
            //獲取之前檢查一下焦辅,數(shù)據(jù)數(shù)組是否在之前被修改過
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        //這是一個訪問者模式,以后使用這個模式椿胯,還是繼承Consumer筷登,劃算
        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            //判斷是否為空
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            
            //iterator 已經(jīng)遍歷完成
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            //檢查數(shù)據(jù)數(shù)組是否被修改
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            
            //循環(huán)便利
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // 更新游標(biāo)
            cursor = i;
            lastRet = i - 1;
            //檢查數(shù)據(jù)是否被修改
            checkForComodification();
        }

        //檢查元素在使用iterator 修改之前,是否被修改過
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

SubList

子字符串哩盲,實際上公用的是原始的數(shù)組

  private class SubList extends AbstractList<E> implements RandomAccess {
        private final AbstractList<E> parent;
        private final int parentOffset;
        private final int offset;
        int size;

        SubList(AbstractList<E> parent,
                int offset, int fromIndex, int toIndex) {
            //從這里可以看出來前方,持有的是原始的字符串引用, 記錄偏移量的廉油,從而達(dá)到操作子字符串的目的    
            this.parent = parent;
            this.parentOffset = fromIndex;
            this.offset = offset + fromIndex;
            this.size = toIndex - fromIndex;
            this.modCount = ArrayList.this.modCount;
        }

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

        public E get(int index) {
            rangeCheck(index);
            checkForComodification();
            return ArrayList.this.elementData(offset + index);
        }

        public int size() {
            checkForComodification();
            return this.size;
        }

        public void add(int index, E e) {
            rangeCheckForAdd(index);
            checkForComodification();
            parent.add(parentOffset + index, e);
            this.modCount = parent.modCount;
            this.size++;
        }

        public E remove(int index) {
            rangeCheck(index);
            checkForComodification();
            E result = parent.remove(parentOffset + index);
            this.modCount = parent.modCount;
            this.size--;
            return result;
        }

        protected void removeRange(int fromIndex, int toIndex) {
            checkForComodification();
            parent.removeRange(parentOffset + fromIndex,
                               parentOffset + toIndex);
            this.modCount = parent.modCount;
            this.size -= toIndex - fromIndex;
        }

        public boolean addAll(Collection<? extends E> c) {
            return addAll(this.size, c);
        }

        public boolean addAll(int index, Collection<? extends E> c) {
            rangeCheckForAdd(index);
            int cSize = c.size();
            if (cSize==0)
                return false;

            checkForComodification();
            parent.addAll(parentOffset + index, c);
            this.modCount = parent.modCount;
            this.size += cSize;
            return true;
        }

        public Iterator<E> iterator() {
            return listIterator();
        }

        public ListIterator<E> listIterator(final int index) {
            checkForComodification();
            rangeCheckForAdd(index);
            final int offset = this.offset;

            return new ListIterator<E>() {
                int cursor = index;
                int lastRet = -1;
                int expectedModCount = ArrayList.this.modCount;

                public boolean hasNext() {
                    return cursor != SubList.this.size;
                }

                @SuppressWarnings("unchecked")
                public E next() {
                    checkForComodification();
                    int i = cursor;
                    if (i >= SubList.this.size)
                        throw new NoSuchElementException();
                    Object[] elementData = ArrayList.this.elementData;
                    if (offset + i >= elementData.length)
                        throw new ConcurrentModificationException();
                    cursor = i + 1;
                    return (E) elementData[offset + (lastRet = i)];
                }

                public boolean hasPrevious() {
                    return cursor != 0;
                }

                @SuppressWarnings("unchecked")
                public E previous() {
                    checkForComodification();
                    int i = cursor - 1;
                    if (i < 0)
                        throw new NoSuchElementException();
                    Object[] elementData = ArrayList.this.elementData;
                    if (offset + i >= elementData.length)
                        throw new ConcurrentModificationException();
                    cursor = i;
                    return (E) elementData[offset + (lastRet = i)];
                }

                @SuppressWarnings("unchecked")
                public void forEachRemaining(Consumer<? super E> consumer) {
                    Objects.requireNonNull(consumer);
                    final int size = SubList.this.size;
                    int i = cursor;
                    if (i >= size) {
                        return;
                    }
                    final Object[] elementData = ArrayList.this.elementData;
                    if (offset + i >= elementData.length) {
                        throw new ConcurrentModificationException();
                    }
                    while (i != size && modCount == expectedModCount) {
                        consumer.accept((E) elementData[offset + (i++)]);
                    }
                    // update once at end of iteration to reduce heap write traffic
                    lastRet = cursor = i;
                    checkForComodification();
                }

                public int nextIndex() {
                    return cursor;
                }

                public int previousIndex() {
                    return cursor - 1;
                }

                public void remove() {
                    if (lastRet < 0)
                        throw new IllegalStateException();
                    checkForComodification();

                    try {
                        SubList.this.remove(lastRet);
                        cursor = lastRet;
                        lastRet = -1;
                        expectedModCount = ArrayList.this.modCount;
                    } catch (IndexOutOfBoundsException ex) {
                        throw new ConcurrentModificationException();
                    }
                }

                public void set(E e) {
                    if (lastRet < 0)
                        throw new IllegalStateException();
                    checkForComodification();

                    try {
                        ArrayList.this.set(offset + lastRet, e);
                    } catch (IndexOutOfBoundsException ex) {
                        throw new ConcurrentModificationException();
                    }
                }

                public void add(E e) {
                    checkForComodification();

                    try {
                        int i = cursor;
                        SubList.this.add(i, e);
                        cursor = i + 1;
                        lastRet = -1;
                        expectedModCount = ArrayList.this.modCount;
                    } catch (IndexOutOfBoundsException ex) {
                        throw new ConcurrentModificationException();
                    }
                }

                final void checkForComodification() {
                    if (expectedModCount != ArrayList.this.modCount)
                        throw new ConcurrentModificationException();
                }
            };
        }

        public List<E> subList(int fromIndex, int toIndex) {
            subListRangeCheck(fromIndex, toIndex, size);
            return new SubList(this, offset, fromIndex, toIndex);
        }

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

        private void rangeCheckForAdd(int index) {
            if (index < 0 || index > this.size)
                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }

        private String outOfBoundsMsg(int index) {
            return "Index: "+index+", Size: "+this.size;
        }

        private void checkForComodification() {
            if (ArrayList.this.modCount != this.modCount)
                throw new ConcurrentModificationException();
        }

        public Spliterator<E> spliterator() {
            checkForComodification();
            return new ArrayListSpliterator<E>(ArrayList.this, offset,
                                               offset + this.size, this.modCount);
        }
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末惠险,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子抒线,更是在濱河造成了極大的恐慌班巩,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,946評論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件嘶炭,死亡現(xiàn)場離奇詭異抱慌,居然都是意外死亡,警方通過查閱死者的電腦和手機眨猎,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,336評論 3 399
  • 文/潘曉璐 我一進(jìn)店門抑进,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人睡陪,你說我怎么就攤上這事寺渗。” “怎么了兰迫?”我有些...
    開封第一講書人閱讀 169,716評論 0 364
  • 文/不壞的土叔 我叫張陵稽莉,是天一觀的道長蹄衷。 經(jīng)常有香客問我诱担,道長定血,這世上最難降的妖魔是什么转砖? 我笑而不...
    開封第一講書人閱讀 60,222評論 1 300
  • 正文 為了忘掉前任须鼎,我火速辦了婚禮,結(jié)果婚禮上府蔗,老公的妹妹穿的比我還像新娘晋控。我一直安慰自己,他們只是感情好姓赤,可當(dāng)我...
    茶點故事閱讀 69,223評論 6 398
  • 文/花漫 我一把揭開白布赡译。 她就那樣靜靜地躺著,像睡著了一般不铆。 火紅的嫁衣襯著肌膚如雪蝌焚。 梳的紋絲不亂的頭發(fā)上裹唆,一...
    開封第一講書人閱讀 52,807評論 1 314
  • 那天,我揣著相機與錄音只洒,去河邊找鬼许帐。 笑死,一個胖子當(dāng)著我的面吹牛毕谴,可吹牛的內(nèi)容都是我干的成畦。 我是一名探鬼主播,決...
    沈念sama閱讀 41,235評論 3 424
  • 文/蒼蘭香墨 我猛地睜開眼涝开,長吁一口氣:“原來是場噩夢啊……” “哼循帐!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起舀武,我...
    開封第一講書人閱讀 40,189評論 0 277
  • 序言:老撾萬榮一對情侶失蹤拄养,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后奕剃,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體衷旅,經(jīng)...
    沈念sama閱讀 46,712評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,775評論 3 343
  • 正文 我和宋清朗相戀三年纵朋,在試婚紗的時候發(fā)現(xiàn)自己被綠了柿顶。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,926評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡操软,死狀恐怖嘁锯,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情聂薪,我是刑警寧澤家乘,帶...
    沈念sama閱讀 36,580評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站藏澳,受9級特大地震影響仁锯,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜翔悠,卻給世界環(huán)境...
    茶點故事閱讀 42,259評論 3 336
  • 文/蒙蒙 一业崖、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧蓄愁,春花似錦双炕、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,750評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春站超,著一層夾襖步出監(jiān)牢的瞬間荸恕,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,867評論 1 274
  • 我被黑心中介騙來泰國打工顷编, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留戚炫,地道東北人。 一個月前我還...
    沈念sama閱讀 49,368評論 3 379
  • 正文 我出身青樓媳纬,卻偏偏與公主長得像双肤,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子钮惠,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,930評論 2 361

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

  • Java源碼研究之容器(1) 如何看源碼 很多時候我們看源碼, 看完了以后經(jīng)常也沒啥收獲, 有些地方看得懂, 有些...
    駱駝騎士閱讀 996評論 0 22
  • 四茅糜、集合框架 1:String類:字符串(重點) (1)多個字符組成的一個序列,叫字符串素挽。生活中很多數(shù)據(jù)的描述都采...
    佘大將軍閱讀 764評論 0 2
  • 1蔑赘、揭開ArrayList真面目 作者將在本文詳細(xì)贅述日常開發(fā)中最常用集合類-ArrayList,本次JCF源碼分...
    Ambitor閱讀 477評論 0 1
  • 在面試中經(jīng)常被問到JDK源碼的問題预明,基于大學(xué)時期對數(shù)據(jù)結(jié)構(gòu)和算法的掌握缩赛,雖然能夠答出基本實現(xiàn),但是總給人一種一知半...
    nikola閱讀 339評論 0 0
  • 本篇結(jié)構(gòu): 前言 數(shù)據(jù)結(jié)構(gòu) 重要參數(shù) 常用方法 源碼分析 疑問解答 分析總結(jié) 一撰糠、前言 ArrayList和Lin...
    w1992wishes閱讀 465評論 0 0