import java.util.Iterator; /** * 动态数组 * 成员变量:容器数组arr,元素个数count * 私有方法:调整数组大小resize() * 公开方法:添加元素add()、删除元素delete()、获取大小size()、判断是否为空isEmpty() * 要求:实现泛型、迭代器、 */ public class DynamicArray<Item> implements Iterable<Item> { private Item[] arr; private int count; public DynamicArray() { arr = (Item[])new Object[5]; count = 0; } public DynamicArray(int n) { arr = (Item[])new Object[n]; count = 0; } private void resize(int size){ Item[] temp = (Item[])new Object[size]; for(int i=0;i<arr.length;i++){ temp[i]=arr[i]; } arr = temp; } public void add(Item e){ if(arr.length == count){ resize(2*arr.length); } arr[count]=e; count++; } public boolean delete(Item e){ for(int i=0;i<count;i++){ if(arr[i]==e){ for(int j=i;j<count-1;j++){ arr[j]=arr[j+1]; } arr[count]=null; count--; return true; } } return false; } public int size(){ return count; } public boolean isEmpty(){ if(count==0) return true; return false; } @Override public Iterator<Item> iterator() { return new Iterator<Item>() { int i=0; @Override public boolean hasNext() { if(i<count) return true; return false; } @Override public Item next() { return arr[i++]; } }; } }
/** * 测试案例 */ public class TestCase { public static void main(String[] args) { DynamicArray<Integer> integerDynamicArray = new DynamicArray<>(); integerDynamicArray.add(1); integerDynamicArray.add(2); integerDynamicArray.add(3); integerDynamicArray.add(4); integerDynamicArray.add(5); integerDynamicArray.add(6); integerDynamicArray.add(7); integerDynamicArray.delete(4); System.out.println(integerDynamicArray.size()); System.out.println(integerDynamicArray.isEmpty()); System.out.println("======================"); for(Integer e :integerDynamicArray){ System.out.println(e); } } }
//结果 6 false ====================== 1 2 3 5 6 7