Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @Title Week 7 Discussion
- * @author Adam Hall
- */
- package week7discussion;
- import java.util.ArrayList;
- import java.util.List;
- /**
- *
- * @author adamchall
- */
- //Stack is first in last out
- class ObjectStack {
- private Object[] myStack;
- private int top;
- public ObjectStack(int maxSize) {
- myStack = new Object[maxSize];
- top = -1;
- }
- void Push(Object input) {
- myStack[++top] = input;
- }
- Object Pop() {
- return myStack[top--];
- }
- boolean isEmpty() {
- return (top == -1);
- }
- }
- class GenericStack<T> {
- private List<T> myStack;
- public GenericStack() {
- myStack = new ArrayList<>();
- }
- void Push(T input) {
- myStack.add(input);
- }
- T Pop() {
- T returnValue;
- if (myStack.isEmpty() == true) {
- return null;
- }
- returnValue = myStack.get(myStack.size() - 1);
- myStack.remove(myStack.size() - 1);
- return returnValue;
- }
- T Peek() {
- return myStack.get(myStack.size() - 1);
- }
- boolean isEmpty() {
- return myStack.isEmpty();
- }
- }
- public class Week7Discussion {
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- System.out.println("About to try Generic Stack");
- GenericStack<Double> myDoubleStack = new GenericStack<>();
- myDoubleStack.Push(42.0);
- // Comment this next line out in order to compile, notice it does not compile
- // Because the top is spotted as being not valid at compile time
- // myDoubleStack.Push("Here is a string!"); // This error is caught at compile time
- myDoubleStack.Push(888.8);
- while (!myDoubleStack.isEmpty()) {
- Object objectValue;
- objectValue = myDoubleStack.Pop();
- System.out.println((double) objectValue); // This is not flagged
- }
- System.out.println("About to try ObjectStack");
- ObjectStack myObjectStack = new ObjectStack(10);
- myObjectStack.Push(42.0);
- // Comment this line out to remove RUNTIME error
- myObjectStack.Push("Here is a string!");
- myObjectStack.Push(888.8);
- try {
- while (!myObjectStack.isEmpty()) {
- Object objectValue;
- objectValue = myObjectStack.Pop();
- System.out.println((double) objectValue); // This is not flagged
- }
- } catch (ClassCastException exception) {
- System.out.println(exception);
- System.out.println("This exception points to a programming error that does not show until runtime!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement