在計算機科學中,動態數組,可擴展數組,可調整數組,動態表,可變數組或數組列表是一種隨機存取可變大小列表數據結構,允許添加或刪除元素。它提供許多現代主流編程語言的標准庫。動態數組克服了靜態數組的限制,靜態數組具有需要在分配時指定的固定容量。
代碼實現:
1 package DataStructures; 2 3 import java.util.Iterator; 4 import java.util.NoSuchElementException; 5 6 public class MyArrayList<AnyType> implements Iterable<AnyType> { 7 8 private static final int DEFAULT_CAPACITY=10; 9 private int theSize; 10 private AnyType[] theItems; 11 public MyArrayList() { 12 doClear(); 13 // TODO Auto-generated constructor stub 14 } 15 private void clear(){ 16 doClear(); 17 } 18 private void doClear(){ //移除動態數組中所有元素 19 theSize=0; 20 ensureCapacity(DEFAULT_CAPACITY); 21 } 22 public int size(){ //返回當前動態數組大小 23 return theSize; 24 } 25 public boolean isEmpty(){ 26 return size()==0; 27 } 28 public void trimToSize(){ //將動態數組的容量調整為當前實例的大小 29 ensureCapacity(size()); 30 } 31 public AnyType get(int idx){ 32 if(idx<0||idx>=size()) 33 throw new ArrayIndexOutOfBoundsException(); 34 return theItems[idx]; 35 } 36 public AnyType set(int idx,AnyType newVal){ 37 if(idx<0||idx>=size()) 38 throw new ArrayIndexOutOfBoundsException(); 39 AnyType old =theItems[idx]; 40 theItems[idx]=newVal; 41 return old; 42 } 43 private void ensureCapacity(int newCapacity) { //為當前的動態數組擴容 44 if(newCapacity<theSize) 45 return; 46 AnyType[] old=theItems; 47 theItems=(AnyType []) new Object[newCapacity]; 48 for(int i=0;i<size();i++) 49 theItems[i]=old[i]; 50 } 51 public boolean add(AnyType x){ 52 add(size(),x); 53 return true; 54 } 55 public void add(int idx,AnyType x){ //添加數據 56 if(theItems.length==size()) 57 ensureCapacity(size()*2+1); //進行擴容 58 for(int i=theSize;i>idx;i--){ 59 theItems[i]=theItems[i-1]; 60 } 61 theItems[idx]=x; 62 theSize++; 63 } 64 public AnyType remove(int idx){ 65 AnyType removeItem=theItems[idx]; 66 for(int i=idx;i<size()-1;i++) 67 theItems[i]=theItems[i+1]; 68 theSize--; 69 return removeItem; 70 } 71 @Override 72 public Iterator<AnyType> iterator() { //迭代器iterator方法返回的是ArrayListIterator的一個實例 73 // TODO Auto-generated method stub 74 return new ArrayListIterator(); 75 } 76 private class ArrayListIterator implements Iterator<AnyType>{ 77 private int current=0; 78 public boolean hasNext(){ 79 return current<size(); 80 } 81 public AnyType next(){ 82 if(!hasNext()) 83 throw new NoSuchElementException(); 84 return theItems[current++]; 85 } 86 public void remove(){ 87 MyArrayList.this.remove(--current); 88 } 89 } 90 }