天天看點

ArrayList源碼閱讀----JDK1.8

//定義一個預設的長度10
    private static final int DEFAULT_CAPACITY = 10;
    //定義空的數組
    private static final Object[] EMPTY_ELEMENTDATA = {};
    //定義數組用來存儲放入ArrayList的元素
    private transient Object[] elementData;
    //定義記錄ArrayList中元素的個數
    private int size;
    
    //構造方法--建立指定長度的數組的ArrayList
    public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
    }
    //建立ArrayList數組長度為0的ArrayList,當向其中添加第一個元素的時候,擴充數組的長度為10--預設數組長度
    public ArrayList() {
        super();
        this.elementData = EMPTY_ELEMENTDATA;
    }
    //建立含有指定集合元素的ArrayList,通過集合的toArray()方法傳回一個數組,讓ArrayList的數組指向該數組
    public ArrayList(Collection<? extends E> c) {
    elementData = c.toArray();
    size = elementData.length;
    // c.toArray might (incorrectly) not return Object[] (see 6260652)
    if (elementData.getClass() != Object[].class)
        elementData = Arrays.copyOf(elementData, size, Object[].class);
    }
    //當ArrayList的元素個數小于數組長度時候,将數組的長度減小為ArrayList中元素的個數
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = Arrays.copyOf(elementData, size);
        }
    }
    // 向ArrayList中添加一個元素,添加前先檢查數組的容量,是否需要擴容,再添加元素進去
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    //注意:minCapavity為添加元素時ArrayList需要最小的容量--确定需要的最小容量
    private void ensureCapacityInternal(int minCapacity) {
           if (elementData == 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);
        }

    }
    //控制記憶體溢出使用,對最大容量的限制,最大的數組長度為整型最大值減8
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    //擴充容量:先根據原來的容量擴充為原來的1.5倍,再和最小需要的容量比較,假如還是比需要的小,則将最小需要的指派給數組新容量
   假如新容量比最大的容量大,則再次擴容,擴容完成後将數組原來的内容,複制到新的數組中,其實本質實作還是利用的本地方法
    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) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }      
1 //按照下标進行添加,涉及到下标的先檢查下标是否越界,檢測容量,移動元素,添加元素
  2     public void add(int index, E element) {
  3         rangeCheckForAdd(index);
  4 
  5         ensureCapacityInternal(size + 1);  // Increments modCount!!
  6         System.arraycopy(elementData, index, elementData, index + 1,
  7                          size - index);
  8         elementData[index] = element;
  9         size++;
 10     }
 11     //判斷下标是否越界
 12     private void rangeCheckForAdd(int index) {
 13         if (index > size || index < 0)
 14             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
 15     }
 16     //添加集合中所有元素進入ArrayList,先檢查容量,在複制,修改元素個數
 17     public boolean addAll(Collection<? extends E> c) {
 18         Object[] a = c.toArray();
 19         int numNew = a.length;
 20         ensureCapacityInternal(size + numNew);  // Increments modCount
 21         System.arraycopy(a, 0, elementData, size, numNew);
 22         size += numNew;
 23         return numNew != 0;
 24     }
 25     //從特定下标開始,将集合中的元素加入到ArrayList裡面
 26     public boolean addAll(int index, Collection<? extends E> c) {
 27         rangeCheckForAdd(index);
 28 
 29         Object[] a = c.toArray();
 30         int numNew = a.length;
 31         ensureCapacityInternal(size + numNew);  // Increments modCount
 32 
 33         int numMoved = size - index;
 34         if (numMoved > 0)
 35         System.arraycopy(elementData, index, elementData, index + numNew,
 36                                  numMoved);
 37 
 38         System.arraycopy(a, 0, elementData, index, numNew);
 39         size += numNew;
 40         return numNew != 0;
 41      }
 42     //删除指定下标的元素
 43      public E remove(int index) {
 44             rangeCheck(index);
 45 
 46             modCount++;
 47             E oldValue = elementData(index);
 48 
 49             int numMoved = size - index - 1;
 50             if (numMoved > 0)
 51                 System.arraycopy(elementData, index+1, elementData, index,
 52                                  numMoved);
 53             elementData[--size] = null; // clear to let GC do its work
 54 
 55             return oldValue;
 56       }
 57      //按照對象的内容删除,空和非空兩種情況
 58      public boolean remove(Object o) {
 59             if (o == null) {
 60                 for (int index = 0; index < size; index++)
 61                     if (elementData[index] == null) {
 62                         fastRemove(index);
 63                         return true;
 64                     }
 65             } else {
 66                 for (int index = 0; index < size; index++)
 67                     if (o.equals(elementData[index])) {
 68                         fastRemove(index);
 69                         return true;
 70                     }
 71             }
 72             return false;
 73        }
 74      //将特定的下标的元素設定為指定的元素
 75      public E set(int index, E element) {
 76             rangeCheck(index);
 77 
 78             E oldValue = elementData(index);
 79             elementData[index] = element;
 80             return oldValue;
 81       }
 82      //是否包含特定的元素
 83      public boolean contains(Object o) {
 84             return indexOf(o) >= 0;
 85      }
 86      //傳回特定對象第一次出現的下标,空或非空
 87      public int indexOf(Object o) {
 88             if (o == null) {
 89                 for (int i = 0; i < size; i++)
 90                     if (elementData[i]==null)
 91                         return i;
 92             } else {
 93                 for (int i = 0; i < size; i++)
 94                     if (o.equals(elementData[i]))
 95                         return i;
 96             }
 97             return -1;
 98      }
 99      //特定對象最後一次出現的下标
100      public int lastIndexOf(Object o) {
101             if (o == null) {
102                 for (int i = size-1; i >= 0; i--)
103                     if (elementData[i]==null)
104                         return i;
105             } else {
106                 for (int i = size-1; i >= 0; i--)
107                     if (o.equals(elementData[i]))
108                         return i;
109             }
110             return -1;
111       }
112      //傳回包含ArrayList元素的數組
113      public Object[] toArray() {
114             return Arrays.copyOf(elementData, size);
115      }
116      //傳回一條特定的子ArrayList,SubList在其中是以内部類的形式存在
117      public List<E> subList(int fromIndex, int toIndex) {
118          subListRangeCheck(fromIndex, toIndex, size);
119          return new SubList(this, 0, fromIndex, toIndex);
120      }
121