forked from HarryDulaney/intro-to-java-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExercise19_02.java
70 lines (58 loc) · 1.67 KB
/
Exercise19_02.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package ch_19;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
/**
* 19.2 (Implement ArrayListGenericStack using inheritance) In Listing 19.1, ArrayListGenericStack is
* implemented using composition. Define a new stack class that extends ArrayList.
* Draw the UML diagram for the classes and then implement ArrayListGenericStack.
* <p>
* Write a test program that prompts the user to enter five strings and displays them in
* reverse order.
*/
public class Exercise19_02 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter five String values seperated by space: ");
String[] input = in.nextLine().split(" ");
ArrayListGenericStack<String> stack = new ArrayListGenericStack<>();
for (String s : input) {
stack.push(s);
}
in.close();
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
}
/**
* UML Diagram:
*
* <img src="../../resources/uml-diagrams/exercise19_02.png"/>
*
* @param <E> Type held by the ArrayListGenericStack instance.
*/
class ArrayListGenericStack<E> extends ArrayList<E> {
public int getSize() {
return size();
}
public E peek() {
return get(getSize() - 1);
}
public Object push(E o) {
add(o);
return o;
}
public Object pop() {
Object o = get(getSize() - 1);
remove(getSize() - 1);
return o;
}
public boolean isEmpty() {
return super.isEmpty();
}
@Override
public String toString() {
return "Stack: " + Arrays.toString(super.toArray());
}
}