Skip to content

Commit d380583

Browse files
author
jsquared21
committed
Add Ex 19.2
1 parent f783947 commit d380583

File tree

4 files changed

+57
-0
lines changed

4 files changed

+57
-0
lines changed
1.02 KB
Binary file not shown.
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
}
894 Bytes
Binary file not shown.
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
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+
}

0 commit comments

Comments
 (0)