1. Define the stack interfaces
. 1 public interface Stack <T> { 2 // return stack size . 3 public int size (); . 4 // determines whether the stack is empty . 5 public Boolean isEmpty (); . 6 // stack . 7 public void Push (T T) ; 8 // stack . 9 public Object POP () throws StackEmptyException; 10 // returns the top of the stack . 11 public Object PEEK () throws StackEmptyException; 12 is }
2. custom exception
. 1 public class StackEmptyException the extends a RuntimeException { 2 // new class exception stack is empty . 3 public StackEmptyException (String eMeaasge) { . 4 Super (eMeaasge); . 5 } . 6 }
3. implement an array-stack interface
. 1 public class StackArray <T> the implements Stack <T> { 2 // initial capacity of stack 2; . 3 Private Final int LEN = 2 ; . 4 // pointer stack defined; . 5 Private int Top; . 6 // stack in array achieved . 7 Private T [] Elements; . 8 // constructor initializes . 9 public StackArray () { 10 Top = -1 ; . 11 Elements = (T []) new new Object [LEN]; 12 is } 13 is 14 @Override 15 public int size() { 16 return top+1; 17 } 18 19 @Override 20 public boolean isEmpty() { 21 return top<0; 22 } 23 24 @Override 25 public void push(T t) { 26 if(this.size()==elements.length){ 27 this.expandSize(); 28 } 29 // ++ top, the first increment, and then assigned 30 Elements [Top ++] = T; 31 is } 32 33 is @Override 34 is public Object POP () throws StackEmptyException { 35 IF ( the this .isEmpty ()) { 36 the throw new new StackEmptyException ( "current stack is empty, the stack can not" ); 37 [ } 38 is Object obj = Elements [Top]; 39 // top--, the first assignment, and then from minus 40 Elements [Top -] = null ; 41 is return obj; 42 } 43 is 44 is @Override 45 public Object PEEK () throws StackEmptyException { 46 is IF ( the this .isEmpty ()) { 47 the throw new new StackEmptyException ( "current stack is empty, no content" ); 48 } 49 return Elements [Top]; 50 } 51 // stack capacity expansion 52 is public void expandSize () { 53 is T [] = A (T []) new new Object [elements.length * 2 ]; 54 is for ( int i=0;i<elements.length;i++){ 55 a[i]=elements[i]; 56 } 57 elements=a; 58 } 59 }
4. Test
1 public class Main { 2 3 public static void main(String[] args) { 4 StackArray<Integer> stackArray = new StackArray<Integer>(); 5 System.out.println(stackArray.size()); 6 /* stackArray.pop();*/ 7 stackArray.push(1); 8 stackArray.push(2); 9 stackArray.push(5); 10 stackArray.push(6); 11 System.out.println(stackArray.size()); 12 System.out.println(stackArray.peek()); 13 14 15 } 16 }
5. Test Results