1
+ package ch_19 ;
2
+
3
+ import java .util .Arrays ;
4
+
5
+
6
+ /**
7
+ * 19.1 (Revising Listing 19.1) Revise the ArrayListGenericStack class in Listing 19.1 to implement
8
+ * it using an array rather than an ArrayList. You should check the array size
9
+ * before adding a new element to the stack. If the array is full, create a new array that
10
+ * doubles the current array size and copy the elements from the current array to the
11
+ * new array.
12
+ */
13
+ public class Exercise19_01 {
14
+ //Test
15
+ public static void main (String [] args ) {
16
+ GenericStack <String > stack1 = new GenericStack <>();
17
+ stack1 .push ("Atlanta" );
18
+ stack1 .push ("Memphis" );
19
+ stack1 .push ("New York" );
20
+ stack1 .push ("Columbus" );
21
+ stack1 .push ("Chicago" );
22
+ stack1 .push ("St. Louis" );
23
+ stack1 .push ("New Orleans" );
24
+ stack1 .push ("Boston" );
25
+ stack1 .push ("Atlanta" );
26
+ stack1 .push ("Memphis" );
27
+ stack1 .push ("New York" );
28
+ stack1 .push ("Chicago" );
29
+ stack1 .push ("St. Louis" );
30
+ stack1 .push ("New Orleans" );
31
+ stack1 .push ("Boston" );
32
+ stack1 .push ("Atlanta" );
33
+ stack1 .push ("Memphis" );
34
+ stack1 .push ("New York" );
35
+ stack1 .push ("Columbus" );
36
+ stack1 .push ("Chicago" );
37
+ stack1 .push ("St. Louis" );
38
+ stack1 .push ("New Orleans" );
39
+ stack1 .push ("Boston" );
40
+
41
+ while (stack1 .getSize () > 0 ) {
42
+ System .out .println ("Pop: " + stack1 .pop ());
43
+ }
44
+
45
+ }
46
+ }
47
+
48
+ class GenericStack <E > {
49
+ private static int capacity = 16 ;
50
+ private static final int INCREMENT = 16 ;
51
+ private int size ;
52
+ private E [] list = (E []) new Object [capacity ];
53
+
54
+ public GenericStack () {
55
+ }
56
+
57
+ private void increaseCapacity () {
58
+ capacity += INCREMENT ;
59
+ E [] nuList = (E []) new Object [capacity ];
60
+ for (int i = 0 ; i < list .length ; i ++) {
61
+ nuList [i ] = list [i ];
62
+ }
63
+ list = nuList ;
64
+ }
65
+
66
+ public int getSize () {
67
+ return size ;
68
+ }
69
+
70
+ public E peek () {
71
+ return list [size - 1 ];
72
+ }
73
+
74
+ public void push (E o ) {
75
+ list [size ++] = o ;
76
+ if (size == capacity ) {
77
+ increaseCapacity ();
78
+ }
79
+ }
80
+
81
+ public E pop () {
82
+ if (size > 0 ) {
83
+ return list [--size ];
84
+ } else {
85
+ return null ;
86
+ }
87
+ }
88
+
89
+ public boolean isEmpty () {
90
+ return size == 0 ;
91
+ }
92
+
93
+ @ Override
94
+ public String toString () {
95
+ return "stack: " + Arrays .toString (list );
96
+ }
97
+ }
0 commit comments