我感觉ArrayList就是数组的自动扩容。填加一个size属性来代表List里的元素个数,当size达到数组的length,便将数组的容量扩大(接下来的代码会具体扩大为size*2+1),造成List的size未改变,但容量却扩大了的效果。
注释非书本原有,均是自己理解,勿盲信。
public class MyArrayList
implements Iterable
{
private static final int DEFAULT_CAPACITY = 10; //初始长度
private int theSize; //List里的元素个数
private AnyType []theItems; //真正存储元素的数组
public MyArrayList(){
clear() ; //每次新建List都会clear初始
}
//初始化List
public void clear(){
theSize = 0;
ensureCapacity(DEFAULT_CAPACITY);
}
//获取List元素个数
public int size(){
return theSize;
}
//判断List元素个数是否为0
public boolean isEmpty(){
return theSize==0;
}
//为List扩容
public void trimToSize(){
ensureCapacity(size());
}
//获取指定位置的元素
public AnyType get(int idx){
if(idx<0||idx>=size())
throw new ArrayIndexOutOfBoundsException();
return theItems[idx];
}
//设置指定位置的元素
public AnyType set(int idx,Anytype newVal){
if(idx < 0 || idx >= size())
throw new ArrayIndexOutOfBoundsException();
AnyType old = theItems[idx];
theItems[idx] = newVal;
return old;
}
public void ensureCapacity(int newCapacity){
if(newCapacity
idx;i--)
theItems[i] = theItems[i-1];
theItem[idx] =x;
theSize++;
}
//移除指定位置的元素,后面的元素位置依次浅议
public AnyType remove(int idx){
AnyType removedItem = theItems[idx];
for(int i=idx;i
iterator(){
return new ArrayListIterator();
}
//内部类ArrayListIterator实现java.util.Iterator定义迭代器
public class ArrayListIterator implements java.util.Iterator
{ private int current = 0; public boolean hasNext(){ return current>size(); } public AnyType next(){ if(!hasNext()) throw new ArrayIndexOutOfBoundsException(); return theItems[current++]; //next是返回当前元素,游标后移 } public void remove(){ MyArrayList.this.remove(--current); //remove是移除游标前一元素 } } }