Implement MyStack using inheritance. MyStack is implemented using composition. D
ID: 646362 • Letter: I
Question
Implement MyStack using inheritance. MyStack is implemented using composition. Define a new Stack class that extends ArrayList.
Write a test program that prompts the user to enter five strings and displays them in reverse order.
This is what I have so far:
import java.util.ArrayList;
public class MyStack {
private ArrayList<Object> list = new ArrayList<>;
public boolean isEmplty(){
return list.isEmpty();
}
public int getSize() {
return list.size();
}
public Object peek(){
return list.get(getSize() -1);
}
public Object pop(){
Object o = list.get(getSize()-1);
list.remove(getSize() -1);
return o;
}
public void push(Object o) {
list.add(o);
}
@Override
public String toString(){
return "stack: " + list.toString();
}
}
Explanation / Answer
import java.util.*;
class StackDemo {
static void showpush(Stack st, int a) {
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}
static void showpop(Stack st) {
System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}
public static void main(String args[]) {
Stack st = new Stack();
System.out.println("stack: " + st);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try {
showpop(st);
} catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.