Java集合框架--ArrayList

collection框架的接口繼承樹(圖片來自網(wǎng)絡(luò))

ArrayList(圖片來自網(wǎng)絡(luò))

Collection 接口

代碼注釋說明:
The root interface in the collection hierarchy. A collection
represents a group of objects, known as its elements. Some
collections allow duplicate elements and others do not. Some are ordered
and others unordered. The JDK does not provide any direct
implementations of this interface: it provides implementations of more
specific subinterfaces like Set and List. This interface
is typically used to pass collections around and manipulate them where
maximum generality is desired.

接口定義的方法

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 removeAll(Collection<?> c);
default boolean removeIf(Predicate<? super E> filter)
boolean retainAll(Collection<?> c);
void clear();
boolean equals(Object o);
int hashCode();
default Stream<E> stream()
default Stream<E> parallelStream()

List接口

An ordered collection (also known as a sequence). The user of this
interface has precise control over where in the list each element is
inserted. The user can access elements by their integer index (position in
the list), and search for elements in the list


ArrayList實現(xiàn)類

Resizable-array implementation of the List interface. Implements
all optional list operations, and permits all elements, including
null. In addition to implementing the List interface,
this class provides methods to manipulate the size of the array that is
used internally to store the list. (This class is roughly equivalent to
Vector, except that it is unsynchronized.)

    /**
     * 默認數(shù)組的初始化容量
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.
     */
    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.
     */
    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.
     */
    transient Object[] elementData; // non-private to simplify nested class access簡化嵌套類訪問的非私有入口

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;
    /**
     * Constructs an empty list with the specified initial capacity.
     *
     * @param  initialCapacity  the initial capacity of the list
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     */
    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);
        }
    }

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }


    /**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(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);//這句執(zhí)行后如果超過int的最大值那么newCapacity會是一個負數(shù)懒叛,這個需要了解一下數(shù)字二進制的加減原理衫画。
        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;
    }


    /**
     * Returns the element at the specified position in this list.
     *
     * @param  index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }

    /**
     * Checks if the given index is in range.  If not, throws an appropriate
     * runtime exception.  This method does *not* check if the index is
     * negative: It is always used immediately prior to an array access,
     * which throws an ArrayIndexOutOfBoundsException if index is negative.
     */
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
modCount用來干嘛的掐松?
  • 記錄內(nèi)部修改次數(shù)
  • 迭代器(Iterator)每調(diào)用一次next()函數(shù)都會調(diào)用checkForComodification方法判斷一次,此方法用來判斷創(chuàng)建迭代對象的時候List的modCount與現(xiàn)在List的modCount是否一樣鸣驱,不一樣的話就報ConcurrentModificationException異常,這就是所謂的fail-fast策略圆仔,快速失敗機制勒奇。

迭代器遍歷元素

ArrayList的iterator() 方法

   /**
     * Returns an iterator over the elements in this list in proper sequence.
     *
     * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
     *
     * @return an iterator over the elements in this list in proper sequence
     */
public Iterator<E> iterator() {
        return new Itr();
    }

        @SuppressWarnings("unchecked")
        public E next() {
            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];
        }
//expectedModCount 創(chuàng)建對象時獲取的modCount值
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

ArrayList 在循環(huán)中刪除會出現(xiàn)的問題

for循環(huán):

List<Integer> list = new ArrayList<>();
       list.add(1);
       list.add(2);
       list.add(3);
       list.add(3);
       list.add(4);
       list.add(5);
       Integer value = null;

       for (int i = 0; i < list.size(); i++) {
           if (list.get(i) == 3) {
               list.remove(3);
           }
       }
//打印結(jié)果
1
2
3
4
5

這時候會發(fā)現(xiàn)連續(xù)兩個3會跳過一個。原因就是在刪除一個元素的時候濒募,list元素會移位鞭盟,去補齊被刪除的位置,這時候瑰剃,i++了就會跳過原來被刪除的位置齿诉。

Iterator

       Iterator iter = list.iterator();
        while (iter.hasNext()) {
            value = (Integer)iter.next();
            if (value == 3) {
                iter.remove();
            }
        }
//打印結(jié)果
1
2
4
5
      // cursor 指向當前元素的下一個元素的下標  size list的大小
        public boolean hasNext() {
            return cursor != size;
        }
        public E next() {
            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;  //cursor 往后移一位
            return (E) elementData[lastRet = i]; //返回當前元素,并將lastRet 賦值為當前返回元素下標
        }

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

            try {
                ArrayList.this.remove(lastRet); //調(diào)用ArrayList的刪除方法刪除上一次返回的元素
                cursor = lastRet; //下一個元素的下標賦值為當前被刪除的下標
                lastRet = -1;  // 
                expectedModCount = modCount; //為了保證不拋異常晌姚,更新Itr類的expectedModCount
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

根據(jù)上述代碼鹃两,next() 方法會先把cursor的值賦值給下標i,并返回下標為i的元素舀凛,并會俊扳,將cursor + 1 操作, lastRet 被賦值為當前被刪除的元素的下標猛遍。

在remove()中 主要刪除邏輯交給了ArrayList的remove()方法馋记,刪除過程cursor被賦值為lastRet(ArrayList刪除后會把被刪除的位置補齊,保證下一次訪問不會漏掉)懊烤, lastRet被賦值為 -1 (代表上一次返回的元素已經(jīng)被刪除的標記)

foreach:

        for (Integer i : list) {
            if (i == 3) {
                list.remove(3);
            }
        }
//程序會出錯java.util.ConcurrentModificationException

這里就很精彩了梯醒,調(diào)用foreach,程序會執(zhí)行兩條語句分別是:
Itr.hasNext();
Itr.next();
但是在刪除的時候卻是list.remove();
這會導致modCount 和 expectedModCount不一致了
下一次next()的時候 執(zhí)行到 checkForComodification()就會出錯啦~

final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市腌紧,隨后出現(xiàn)的幾起案子茸习,更是在濱河造成了極大的恐慌,老刑警劉巖壁肋,帶你破解...
    沈念sama閱讀 221,198評論 6 514
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件号胚,死亡現(xiàn)場離奇詭異,居然都是意外死亡浸遗,警方通過查閱死者的電腦和手機猫胁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,334評論 3 398
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來跛锌,“玉大人弃秆,你說我怎么就攤上這事媒峡∮破” “怎么了?”我有些...
    開封第一講書人閱讀 167,643評論 0 360
  • 文/不壞的土叔 我叫張陵抗愁,是天一觀的道長郑藏。 經(jīng)常有香客問我衡查,道長,這世上最難降的妖魔是什么译秦? 我笑而不...
    開封第一講書人閱讀 59,495評論 1 296
  • 正文 為了忘掉前任峡捡,我火速辦了婚禮,結(jié)果婚禮上筑悴,老公的妹妹穿的比我還像新娘们拙。我一直安慰自己,他們只是感情好阁吝,可當我...
    茶點故事閱讀 68,502評論 6 397
  • 文/花漫 我一把揭開白布砚婆。 她就那樣靜靜地躺著,像睡著了一般突勇。 火紅的嫁衣襯著肌膚如雪装盯。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,156評論 1 308
  • 那天甲馋,我揣著相機與錄音埂奈,去河邊找鬼。 笑死定躏,一個胖子當著我的面吹牛账磺,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播痊远,決...
    沈念sama閱讀 40,743評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼垮抗,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了碧聪?” 一聲冷哼從身側(cè)響起冒版,我...
    開封第一講書人閱讀 39,659評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎逞姿,沒想到半個月后辞嗡,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,200評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡滞造,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,282評論 3 340
  • 正文 我和宋清朗相戀三年欲间,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片断部。...
    茶點故事閱讀 40,424評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡猎贴,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出蝴光,到底是詐尸還是另有隱情她渴,我是刑警寧澤,帶...
    沈念sama閱讀 36,107評論 5 349
  • 正文 年R本政府宣布蔑祟,位于F島的核電站趁耗,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏疆虚。R本人自食惡果不足惜苛败,卻給世界環(huán)境...
    茶點故事閱讀 41,789評論 3 333
  • 文/蒙蒙 一满葛、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧罢屈,春花似錦嘀韧、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,264評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至曼月,卻和暖如春谊却,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背哑芹。 一陣腳步聲響...
    開封第一講書人閱讀 33,390評論 1 271
  • 我被黑心中介騙來泰國打工炎辨, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人聪姿。 一個月前我還...
    沈念sama閱讀 48,798評論 3 376
  • 正文 我出身青樓蹦魔,卻偏偏與公主長得像,于是被迫代替她去往敵國和親咳燕。 傳聞我的和親對象是個殘疾皇子勿决,可洞房花燭夜當晚...
    茶點故事閱讀 45,435評論 2 359

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