1. 程式人生 > >【JDK】ArrayList集合 原始碼閱讀

【JDK】ArrayList集合 原始碼閱讀

       這是博主第二次讀ArrayList 原始碼,第一次是在很久之前了,當時讀起來有些費勁,記得那時候HashMap的原始碼還是雜湊表+連結串列的資料結構。

       時隔多年,再次閱讀起來ArrayList感覺還蠻簡單的,但是HashMap已經不是當年的HashMap了,所以下一篇會寫HashMap的。

起因:最近寫了一個簡單的檔案校驗方法,然後犯了一些比較低階的錯誤,博主的師兄在進行釋出CR時,提出了一些建議,博主感覺羞愧難當,特此記錄一下,諸君共勉。程式碼以及建議如下,已做脫敏處理:

    /**
     * 修改前
     */
    public String checkFileWithJveye() {
        //建立 sftp連結,獲取目錄下所有檔案列表集合
        List<String> remoteSftpFileList = getRemoteSftpFileList();
        //獲取伺服器已下載列表檔案集合(以XXX結尾的)
        List<String> localFileList = getLocalFileList();
        //已經存在的檔案-remove
        for (int i = 0; i < remoteSftpFileList.size(); i++) {
            if (localFileList.contains(remoteSftpFileList.get(i))) {
                remoteSftpFileList.remove(i);
            }
        }
        return remoteSftpFileList.toString();
    }
/**
 * 師兄的批註:
 * Master @XXXX 大約 6 小時之前
 *         不應該在迴圈內進行 list.remove(index) 操作,當remove一個元素之後,
 *         list會調整順序,size() 會重新計算len,但是i還是原來的值,
 *         導致list有些值沒有被迴圈到。推薦使用迭代器 list.iterator(),
 *         或者將返回的型別改為set,空間換時間,這樣速度也能快些。
 * 討論中師兄從原始碼方面解釋了ArrayList使用的是遍歷Remove,而HashSet直接通過Hash值進行Remove效率更高。
 */


    /**
     * 修改後
     */
    public String checkFileWithJveye2() {
        //建立 sftp連結,獲取目錄下所有檔案列表集合
        Set<String> remoteSftpFiles = getRemoteSftpFileList();
        //獲取伺服器已下載列表檔案集合(以XXX結尾的)
        Set<String> localFiles = getLocalFileList();
        //已經存在的檔案-remove
        for (Iterator<String> it = remoteSftpFiles.iterator(); it.hasNext(); ) {
            String fileName = it.next();
            if (localFiles.contains(fileName)) {
                it.remove();
            }
        }
        //返回未獲取檔案的列表
        return remoteSftpFiles.toString();
    }

       因此博主重讀了ArrayList等原始碼,都是複製的原始碼,方便閱讀,省去了很多年東西(本來東西也不多),只有簡單的增刪改,繼承關係圖如下:

程式碼如下:

import java.util.*;

/**
 * ArrayList簡單的增刪改查
 * @param <E>
 */
public class Bag<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable{

    /**
     * Default initial capacity.
     * 預設的初始化容量
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.
     * EMPTY_CAPACITY
     */
    //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.
     * DEFAULT_CAPACITY
     */
    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.
     *
     * non-private to simplify nested class access      非私有簡化巢狀類的使用。
     */
    transient Object[] elementData;

    /**
     * The size of the ArrayList (the number of elements it contains).
     * 集合中元素的個數
     * @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;




    /**
     * Constructs an empty list with an initial capacity of ten.
     * 初始化構造方法-這裡只保留了一個
     */
    public Bag() {
        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})
     */
    @Override
    public boolean add(E e) {
        // Increments modCount!!
        ensureCapacityInternal(size + 1);
        elementData[size++] = e;
        return true;
    }
    public void ensureCapacityInternal(int minCsap){
        minCsap=minCsap>=DEFAULT_CAPACITY?minCsap:DEFAULT_CAPACITY;
        if (minCsap - elementData.length > 0){
            grow(minCsap);
        }

    }
    /**
     * 查
     * 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}
     */
    @Override
    public E get(int index) {
        if (index >= size){
            throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size());
        }


        return elementData(index);
    }
    // Positional Access Operations

    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }
    /**
     * 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);
        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) {
        // overflow
        if (minCapacity < 0){
            throw new OutOfMemoryError
                    ("Required array size too large");
        }
        return (minCapacity > MAX_ARRAY_SIZE) ?
                Integer.MAX_VALUE :
                MAX_ARRAY_SIZE;
    }


    /**
     *刪
     * 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}
     */
    @Override
    public E remove(int index) {
        //驗證index
        rangeCheck(index);
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0){
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        }
        // clear to let GC do its work?
        elementData[--size] = null;
        return oldValue;
    }
    private void rangeCheck(int index) {
        if (index >= size){
            throw new IndexOutOfBoundsException("Index:+index+, Size: +size()");
        }

    }

    /**
     * 刪
     * Removes the first occurrence of the specified element from this list,
     * if it is present.  If the list does not contain the element, it is
     * unchanged.  More formally, removes the element with the lowest index
     * <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
     * (if such an element exists).  Returns <tt>true</tt> if this list
     * contained the specified element (or equivalently, if this list
     * changed as a result of the call).
     *
     * @param o element to be removed from this list, if present
     * @return <tt>true</tt> if this list contained the specified element
     */
    @Override
    public boolean remove(Object o){
        if(o==null){
            for (int i=0;i<elementData.length;i++){
                if(elementData[i]==null){
                    fastRemove(i);
                    return true;
                }
            }
        }else{
            for (int i=0;i<elementData.length;i++){
                if(o.equals(elementData[i])){
                    fastRemove(i);
                    return true;
                }
            }

        }
        return false;
    }
    /**
     * arrayCopy( arr1, 2, arr2, 5, 10);
     * 意思是;將arr1數組裡從索引為2的元素開始, 複製到陣列arr2裡的索引為5的位置, 複製的元素個數為10個.
     */
    private void fastRemove(int index){
        int numMoved = size - index - 1;
        if (numMoved > 0){
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        }
        // clear to let GC do its work
        elementData[--size] = null;
    }




    /**
     * Returns the number of elements in this list.
     *
     * @return the number of elements in this list
     */
    @Override
    public int size() {
        return size;
    }

    /**
     * Returns <tt>true</tt> if this list contains no elements.
     *
     * @return <tt>true</tt> if this list contains no elements
     */
    @Override
    public boolean isEmpty() {
        return size == 0;
    }


}