File tree Expand file tree Collapse file tree 4 files changed +57
-0
lines changed
Exercise_19/Exercise_19_02 Expand file tree Collapse file tree 4 files changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**********************************************************************************
2
+ * (Implement GenericStack using inheritance) In Listing 19.1, GenericStack is *
3
+ * implemented using composition. Define a new stack class that extends ArrayList. *
4
+ * *
5
+ * Draw the UML diagram for the classes and then implement GenericStack. *
6
+ * Write a test program that prompts the user to enter five strings and displays *
7
+ * them in reverse order. *
8
+ **********************************************************************************/
9
+ import java .util .Scanner ;
10
+
11
+ public class Exercise_19_02 {
12
+ /** Main method */
13
+ public static void main (String [] args ) {
14
+ // Create a Scanner
15
+ Scanner input = new Scanner (System .in );
16
+
17
+ // Create a Stack
18
+ GenericStack <String > stack = new GenericStack <>();
19
+
20
+ // Prompt the user to enter five strings
21
+ System .out .print ("Enter five strings: " );
22
+ for (int i = 0 ; i < 5 ; i ++)
23
+ stack .push (input .next ());
24
+
25
+ // Display the strings in reverse order
26
+ while (!stack .isEmpty ())
27
+ System .out .print (stack .pop () + " " );
28
+ System .out .println ();
29
+ }
30
+ }
Original file line number Diff line number Diff line change
1
+ import java .util .ArrayList ;
2
+
3
+ public class GenericStack <E > extends ArrayList <E > {
4
+
5
+ /** Return the element at the top of the stack */
6
+ public E peek () {
7
+ return get (size () - 1 );
8
+ }
9
+
10
+ /** Push and element on to the stack */
11
+ public void push (E o ) {
12
+ add (o );
13
+ }
14
+
15
+ /* Return and remove the element
16
+ * on the top of the stack */
17
+ public E pop () {
18
+ E o = get (size () - 1 );
19
+ remove (size () - 1 );
20
+ return o ;
21
+ }
22
+
23
+ @ Override // Override the string method in the ArrayList class
24
+ public String toString () {
25
+ return "stack: " + super .toString ();
26
+ }
27
+ }
You can’t perform that action at this time.
0 commit comments