public boolean add(E e){
ensureCapacity(size 1);//确保内部数组有足够的空间
elementData[size ]=e;//将元素加入到数组的末尾,完成添加
return true;
}
public vod ensureCapacity(int minCapacity){
modCount ;
int oldCapacity=elementData.length;
if(minCapacity>oldCapacity){ //如果数组容量不足,进行扩容
Object[] oldData=elementData;
int newCapacity=(oldCapacity*3)/2 1; //扩容到原始容量的1.5倍
if(newCapacitty<minCapacity) //如果新容量小于最小需要的容量,则使用最小
//需要的容量大小
newCapacity=minCapacity ; //进行扩容的数组复制
elementData=Arrays.copyof(elementData,newCapacity);
}
}
public boolean add(E e){
addBefore(e,header);//将元素增加到header的前面
return true;
}
private Entry<E> addBefore(E e,Entry<E> entry){
Entry<E> newEntry = new Entry<E>(e,entry,entry.previous);
newEntry.provious.next=newEntry;
newEntry.next.previous=newEntry;
size ;
modCount ;
return newEntry;
}
public void add(int index,E element){
if(index>size||index<0)
throw new IndexOutOfBoundsException(
"Index:" index ",size: " size);
ensureCapacity(size 1);
System.arraycopy(elementData,index,elementData,index 1,size-index);
elementData[index] = element;
size ;
}
public void add(int index,E element){
addBefore(element,(index==size?header:entry(index)));
}
public E remove(int index);
public E remove(int index){
RangeCheck(index);
modCount ;
E oldValue=(E) elementData[index];
int numMoved=size-index-1;
if(numMoved>0)
System.arraycopy(elementData,index 1,elementData,index,numMoved);
elementData[--size]=null;
return oldValue;
}
public E remove(int index){
return remove(entry(index));
}
private Entry<E> entry(int index){
if(index<0 || index>=size)
throw new IndexOutBoundsException("Index:" index ",size:" size);
Entry<E> e= header;
if(index<(size>>1)){//要删除的元素位于前半段
for(int i=0;i<=index;i )
e=e.next;
}else{
for(int i=size;i>index;i--)
e=e.previous;
}
return e;
}
public ArrayList(){
this(10);
}
public ArrayList (int initialCapacity){
super();
if(initialCapacity<0)
throw new IllegalArgumentException("Illegal Capacity:" initialCapacity)
this.elementData=new Object[initialCapacity];
}
public ArrayList(int initialCapacity)
String tmp;
long start=System.currentTimeMills(); //ForEach
for(String s:list){
tmp=s;
}
System.out.println("foreach spend:" (System.currentTimeMills()-start));
start = System.currentTimeMills();
for(Iterator<String> it=list.iterator();it.hasNext();){
tmp=it.next();
}
System.out.println("Iterator spend;" (System.currentTimeMills()-start));
start=System.currentTimeMills();
int size=;list.size();
for(int i=0;i<size;i ){
tmp=list.get(i);
}
System.out.println("for spend;" (System.currentTimeMills()-start));