21.1

 1 public class Test_21_1<E> {
 2     private int size;
 3     private static final int CAPACITY = 3;
 4     private E array[];
 5     
 6     public Test_21_1(){
 7         this(CAPACITY);
 8     }
 9     
10     public Test_21_1(int n){
11         array = (E[]) new Object[n];
12     }
13     
14     public int getSize(){
15         return size;
16     }
17     
18     public E peek(){
19         // return the top value
20         return array[size - 1];
21     }
22     
23     public void push(E o){
24         //add element
25         if(size >= array.length) {
26             Object[] temp = new Object[array.length * 2];
27             System.arraycopy(array, 0, temp, 0, array.length);
28             array = (E[]) temp;
29         }
30         array[size++] = o;
31     }
32     
33     public E pop(){
34         //return and remove the top element
35         return array[--size];
36     }
37     
38     public boolean isEmpty(){
39         return size == 0;
40     }
41     
42     public static void main(String[] args) {
43         // TODO Auto-generated method stub
44         int j;
45         Test_21_1<String> t = new Test_21_1<String>();
46 
47         t.push("red");
48         t.push("blue");
49         t.push("black");
50         
51         j = t.size;
52 //        for( int i = 0; i < j; i++)
53 //        System.out.println(t.pop());
54 //        System.out.println(t.peek());
55     }
56 
57 }
View Code
原文地址:https://www.cnblogs.com/wanjiang/p/5747861.html