主要的难点在于:
1. 泛型的使用
2. 内存的动态开辟
3. 深度拷贝与浅拷贝的区别(line 30)
1 package xxx.xxxxxxx; 2 3 import java.util.EmptyStackException; 4 5 public class ArrayStack<E> implements Cloneable { 6 7 private E[] data; 8 private int manyItems; 9 10 public ArrayStack() { 11 final int INITIAL_CAPACITY = 10; 12 manyItems = 0; 13 data = (E[]) new Object[INITIAL_CAPACITY]; 14 } 15 16 public ArrayStack(int initialCapacity) { 17 if (initialCapacity < 0) 18 throw new IllegalArgumentException("initialCapacity is negative: " + initialCapacity); 19 manyItems = 0; 20 data = (E[]) new Object[initialCapacity]; 21 } 22 23 public ArrayStack<E> clone() { 24 ArrayStack<E> copy; 25 try { 26 copy = (ArrayStack<E>) super.clone(); 27 } catch (CloneNotSupportedException e) { 28 throw new RuntimeException("This class does not implement Cloneable"); 29 } 30 copy.data = data.clone(); 31 return copy; 32 } 33 34 public void ensureCapacity(int minimumCapacity) { 35 E biggerArray[]; 36 if (data.length < minimumCapacity) { 37 biggerArray = (E[]) new Object[minimumCapacity]; 38 System.arraycopy(data, 0, biggerArray, 0, manyItems); 39 data = biggerArray; 40 } 41 } 42 43 public int getCapacity() { 44 return data.length; 45 } 46 47 public boolean isEmpty() { 48 return manyItems == 0; 49 } 50 51 public E peek() { 52 if (manyItems == 0) 53 throw new EmptyStackException(); 54 return data[manyItems - 1]; 55 } 56 57 public E pop() { 58 if (manyItems == 0) 59 throw new EmptyStackException(); 60 return data[--manyItems]; 61 } 62 63 public void push(E e) { 64 if (manyItems == data.length) 65 ensureCapacity(manyItems * 2 + 1); 66 data[manyItems++] = e; 67 } 68 69 public int size() { 70 return manyItems; 71 } 72 73 public void trimToSize() { 74 E trimmedArray[]; 75 if (data.length != manyItems) { 76 trimmedArray = (E[]) new Object[manyItems]; 77 System.arraycopy(data, 0, trimmedArray, 0, manyItems); 78 data = trimmedArray; 79 } 80 } 81 82 public int remainedCapacity() { 83 return data.length - manyItems; 84 } 85 }