jdk_Collection_ArrayList源碼

package com.collection.List;


import java.util.Arrays;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.NoSuchElementException;
import com.collection.Iterotor.Iterator;


public class ArrayList<E> implements List<E> {
private transient Object[] elementData;
private int size;
private int modCount;
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
 
public ArrayList() {
       this(10);
   }

public ArrayList(int initialCapacity) {
super();
       if (initialCapacity < 0)
           throw new IllegalArgumentException("Illegal Capacity: "+
                                              initialCapacity);
       this.elementData = new Object[initialCapacity];
}


@Override
public boolean add(Object e) {
   ensureCapacityInternal(size + 1); 
   elementData[size++] = e;
        return true;
}


private void ensureCapacityInternal(int minCapacity) {
modCount++;//被修改次數
 
if(minCapacity-elementData.length>0)
{
grow(minCapacity);
}

}


private void grow(int minCapacity) {
int oldCapacity = elementData.length;
int newCapacity = oldCapacity+(oldCapacity>>1); //1.5倍增加新容量

if(newCapacity-minCapacity<0)   //新容量 不夠裝 所需容量  ----->所需容量賦值給 新容量
{
newCapacity = minCapacity;
}
if (newCapacity - MAX_ARRAY_SIZE > 0) //新容量大於(Integer最大-8)
{
           newCapacity = hugeCapacity(minCapacity);
}
elementData = Arrays.copyOf(elementData, newCapacity);
}


private int hugeCapacity(int minCapacity) {
//下標是否越界(當最大Integer在加1 爲負數 此處判斷越界)    當前所需容量大於(Integer最大-8) 賦值爲最大Integer  否則當前容量是  (Integer最大-8)
if (minCapacity < 0) // overflow
           throw new OutOfMemoryError();
       return (minCapacity > MAX_ARRAY_SIZE) ?
           Integer.MAX_VALUE :
           MAX_ARRAY_SIZE;
}


@Override
public E get(int index) {
if(index>=size)
{
System.out.println("下標索引有錯誤");
}

return elementData(index);
}


private E elementData(int index) {
// TODO Auto-generated method stub
return (E) elementData[index];
}


@Override
public int size() {
// TODO Auto-generated method stub
return size;
}


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


private boolean addAll(int index, Collection<? extends E> c) {
/* rangeCheckForAdd(index);
         int cSize = c.size();
         if (cSize==0)
             return false;


         checkForComodification();
         parent.addAll(parentOffset + index, c);
         this.modCount = parent.modCount;
         this.size += cSize;*/
         return true;
}


@Override
public Iterator<E> iterator() {
// TODO Auto-generated method stub
return new Itr();
}


private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;


        public boolean hasNext() {
            return cursor != size; 
        }


        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor; //光標默認爲0
            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];
        }


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


            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }


        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }


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; // Let gc do its work 設置爲null 讓垃圾回收null 最後一位 沒用引用的空間


       return oldValue;
   }
 
 
private void rangeCheck(int index) {
       if (index >= size)
           throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
   }
 
private String outOfBoundsMsg(int index) {
       return "Index: "+index+", Size: "+size;
   }


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章