jdk源碼解讀之ArrayList

直接上源碼:java

構造函數:
算法

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

其實arrayList的本質是一個數據,只不過這個數組的大小能夠變化。咱們先來看下arraylist的數組是怎麼定義的數組

    /**
     * Constructs an empty list with the specified initial capacity.
     *
     * @param   initialCapacity   the initial capacity of the list
     * @exception IllegalArgumentException if the specified initial capacity
     *            is negative
     */
    public ArrayList(int initialCapacity) {
    super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
    this.elementData = new Object[initialCapacity];
    }

構造函數直接弄了一個10大小的obj對象數組。函數

this.elementData = new Object[initialCapacity];this


講到這裏咱們看下其實只有兩個成員變量:spa

  private static final long serialVersionUID = 8683452581122892189L;

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer.
     */
    private transient Object[] elementData;//元素

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;//list元素數量


看他的核心方法:add
code

    public boolean add(E e) {
    ensureCapacity(size + 1);  // 添加元素的時候先讓數量+1
    elementData[size++] = e;//對應的數組引用放對應的對象
    return true;
    }

這裏面有個比較有意思的方法就是這個ensureCapacit這個方法裏面有對應的擴展數組的算法:對象

   public void ensureCapacity(int minCapacity) {
    modCount++;
    int oldCapacity = elementData.length;//得到最初的數組大小,默認狀況下初始值是10
    if (minCapacity > oldCapacity) {//若是比原先的數組元素大了執行以下操做
        Object oldData[] = elementData;//保存原有的數組元素
        //從新new一個數組
        int newCapacity = (oldCapacity * 3)/2 + 1;
            if (newCapacity < minCapacity)
        newCapacity = minCapacity;
            // minCapacity is usually close to size, so this is a win:
            //從新生成一個數組對象並返回,生成的數組對象大小爲原先的1.5X+1和minCapacity之間較大的那個
            elementData = Arrays.copyOf(elementData, newCapacity);
    }
    }
相關文章
相關標籤/搜索