标签:
实现的MyArrayList实为顺序表结构,其中要实现Iterable时必须在内部实现Iterator,即为该表的迭代器.
1 public class MyArrayList<AntType> implements Iterable<AntType> { 2 @Override 3 public Iterator<AntType> iterator() { //实现接口 4 return new MyIterator(); 5 } 6 private class MyIterator implements Iterator<AntType> { 7 8 private int current = 0; 9 10 @Override 11 public boolean hasNext() { 12 return current < size(); 13 } 14 15 @Override 16 public AntType next() { 17 if(!hasNext()) 18 throw new NoSuchElementException(); 19 return theItems[current ++];//迭代器从第一个元素开始迭代,即theItem[0] 20 } 21 public void remove(){ 22 MyArrayList.this.remove(--current); 23 } 24 } 25 26 private static final int DEFAULT_CAPACITY = 10; //设置默认容量 27 28 private int theSize; //当前大小 29 private AntType [] theItems; //元素对象数组 30 31 public MyArrayList(){ //构造函数,生成空表 32 clear(); 33 } 34 35 public void clear(){ //归为默认(清空) 36 theSize = 0; 37 ensureCapacity(DEFAULT_CAPACITY); 38 } 39 40 public void ensureCapacity(int newCapacity ){ //重置表的容量 41 AntType [] oldItems = theItems; 42 theItems = (AntType []) new Object[newCapacity];//****重新分配空间 注意使用强制转换的方式进行定义 43 for (int i = 0 ; i < theSize; i++){ 44 theItems[i] = oldItems[i]; 45 } 46 } 47 48 public int size(){ //当前使用大小 49 return theSize; 50 } 51 52 public boolean isEmpty(){ //判断是否为空 53 return theSize == 0; 54 } 55 56 public void trimToSize(){ //将表的容量设为当前使用的大小 57 ensureCapacity(size()); 58 } 59 60 public AntType get(int idx){ 61 //判断是否越界的合法性 62 if(idx < 0 || idx >= theSize) 63 throw new ArrayIndexOutOfBoundsException();//越界异常 64 else 65 return theItems[idx]; 66 } 67 68 //替换元素 69 public AntType set(int idx, AntType newVal){ 70 if( idx < 0 || idx >= theSize) 71 throw new ArrayIndexOutOfBoundsException(); 72 AntType oldVal = theItems[idx]; 73 theItems[idx] = newVal; 74 return oldVal; 75 } 76 77 public boolean add( AntType newVal){//末尾添加元素 78 if(theItems.length == size()) 79 ensureCapacity(size() * 2 + 1); 80 set(theSize++ , newVal); 81 return true; 82 } 83 84 public void add( int idx, AntType newVal){//任意位置添加元素 85 if(theItems.length == size()) 86 ensureCapacity(size() * 2 + 1); 87 for(int i = size(); i > idx; i--) 88 theItems[i] = theItems[i - 1]; 89 theItems[idx] = newVal; 90 theSize ++; 91 } 92 93 public AntType remove(int idx) { 94 AntType val = theItems[idx]; 95 for (int i = idx; i < theSize - 1; i++) { 96 theItems[i] = theItems[i + 1]; 97 } 98 theSize--; 99 return val; 100 } 101 }
标签:
原文地址:http://www.cnblogs.com/sunnysola/p/4795852.html