java集合類學習筆記之ArrayList

一、簡述

    ArrayList底層的實現是使用了數組保存全部的數據,全部的操做本質上是對數組的操做,每個ArrayList實例都有一個默認的容量(數組的大小,默認是10),隨着html

  對ArrayList不斷增長元素,默認的數組會不斷的向新數組進行拷貝,因爲ArrayList的內部是經過對數組的操做實現的,因此它是線程不安全的java

二、實現

  a、構造方法:

     AyyarList一共提供了三種構造方法:        數組

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

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    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;
        }
    }
View Code

     在jdk1.8中,ArrayList的無參構造方法默認的是建立了一個空的數組,只有當你第一次添加是時候纔會設置它的默認長度爲10 ,在jdk1.6中無參構造方法默認安全

    的就是建立一個長度爲10 的空數組多線程

  b、定義內部數組:

    

/**
     * 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

    關於transient關鍵字的說明能夠參考個人另一篇博客 java學習筆記之對象序列化app

三、ArrayList的操做

  增長操做:  

    add(E e):  

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

       調用add(E e)方法時首先會調用ensureCapacityInternal(int minCapacity)去判斷是否須要對集合進行擴容,而後默認的將新插入的對象放到內部數組的末尾,ide

    當內部數組須要擴容時,每次直接將數組的長度值原來的兩倍,這種操做的代價是很高的,因此在使用過程當中咱們儘可能避免數組的擴容,當能夠預知數組長度的時候學習

    能夠在構造的時候久指定其長度this

          

 

    add(int index, E element)

    

/**
     * Inserts the specified element at the specified position in this
     * 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) {
        rangeCheckForAdd(index);

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

        在調用add(int index, E element)方法想ArrayList中插入一條數據時,這個方法內部先去判斷傳入的下表是否大於數組的長度。大於的話就會spa

      拋出IndexOutOfBoundsException異常,插入的下表小於數組的長度的時候,再去判斷數組是否須要擴容,最後再調用System.arraycopy方法將數組下表大於傳入

      的index的元素所有後移覺得,並將插入的元素放到index位置

    addAll(Collection<? extends E> c)

  

/**
     * Appends all of the elements in the specified collection to the end of
     * this list, in the order that they are returned by the
     * specified collection's Iterator.  The behavior of this operation is
     * undefined if the specified collection is modified while the operation
     * is in progress.  (This implies that the behavior of this call is
     * undefined if the specified collection is this list, and this
     * list is nonempty.)
     *
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);  // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }

      在調用addAll(Collection<? extends E> c) 插入一個集合時,這個方法內部先去判斷增長這個集合數組是否須要擴容,而後調用

    arraycopy(Object src, int srcPos,Object dest, int destPos,int length)方法將新增長的集合放到數組的末尾

  更新操做:

      

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

      在調用set(int index,E e)方法修改裏面的值時,方法內部先去檢查index下表是都超過數組的最大長度,而後再檢查是否有其餘的線程對這個對象的長度

    進行修改了(因此是線程不安全的,多線程同時操做容易直接拋異常),最後是直接替換數組中下表index對應的值

  刪除操做:

      

/**
     * Removes the element at the specified position in this list.
     * 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++;
        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;
    }

      在調用remove(int index)刪除ArrayList中的數據時,首先校驗傳入的下標index是大於數組的長度,而後取出將要被刪除的數並判斷下標index以後是否還有元素,

    若是有的話將下標以後的元素所有往前移動一位,並最終將刪除的元素的值返回

相關文章
相關標籤/搜索