import java.util.Iterator; public class MyArrayList<AnyType> implements Iterable<AnyType>{ // 初始容量 private static final int DEFAULT_CAPACITY=10; // 當前容量 private int theSize; // 數組成員 private AnyType[] theItems; // 構造方法 用來初始化ArrayList public MyArrayList(){ doClear(); } // 清空list public void clear(){ doClear(); } // 清空list public void doClear(){ theSize=0; ensureCapacity(DEFAULT_CAPACITY); } // 獲取list的size public int size(){ return theSize; } // 判斷是否爲空 public boolean isEmpty(){ return size()==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<theSize) return; // 儲存對原始數組的引用 AnyType[] old = theItems; // 爲新數組分配內存 theItems = (AnyType[]) new Object[newCapacity]; // 將內容拷貝到新的數組中 for (int i = 0; i < size(); i++) { theItems[i] = old[i]; } } // 添加元素到表的末端 public boolean add(AnyType x){ add (size(), x); return true; } // 添加元素到指定的位置 public void add(int idx, AnyType x){ if(theItems.length==size()) ensureCapacity(size()*2+1); // 從最後一個元素的位置+1(也就是theSize)處循環到idx處,把i-1處的項賦值給i,最後把把x賦值給idx處 for (int i = theSize;i>idx;i--) theItems[i] = theItems[i-1]; theItems[idx] = x; theSize++; } // 移除某一項 public AnyType remove(int idx){ AnyType removeItem = theItems[idx]; // 從idx處到最右端,把每一項向左移動,最後theSize-1 for (int i = idx; i < size()-1; i++) theItems[i] = theItems[i+1]; theSize--; return removeItem; } // 實現了iterator,返回一個內部類ArrayListIterator @Override public Iterator<AnyType> iterator() { return new ArrayListIterator(); } /* ArrayListIterator儲存當前位置的概念, 提供hasNext,next,remove的實現.當前位置表示要被查看的下一元素(的數組下標) 所以初始時當前位置爲0 */ private class ArrayListIterator implements java.util.Iterator<AnyType>{ private int current = 0; public boolean hasNext(){ return current<size(); } public AnyType next(){ if(!hasNext()) throw new java.util.NoSuchElementException(); return theItems[current++]; } public void remove(){ MyArrayList.this.remove(--current); } } }
ArrayList的實現
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.