In: Computer Science
public class MyStack<E> {
private ArrayList<E> list = new ArrayList<>();
public int getSize() {
return list.size();
}
public E peek() {
return list.get(getSize() - 1);
}
public void push(E o) {
list.add(o);
}
public E pop() {
E o = list.get(getSize() - 1);
list.remove(getSize() - 1);
return o;
}
public boolean isEmpty() {
return list.isEmpty();
}
@Override
public String toString() {
return "stack: " + list.toString();
}
}
For this exercise, rewrite the MyStack <E> to the GenericStack<E> class that extends from ArrayList<E>.
import java.util.ArrayList;
import java.util.Iterator;
public class A6Q2 {
public static void main(String[] args) {
/* After building your GenericStack from the ArrayList, add codes
here to build the two Stacks
* (String and Integer) here
*/
}
// Build a static class GenericStack<E> extends ArrayList
static class GenericStack<E> extends
ArrayList<E> {
}
}
Since this is a GenericStack<E> class, show that you can
build a String (names) and Integer (Integer) stack using the same
generic class.
In java please. Thank You
Given below is the code for the question. Please do rate the answer if it helped. Thank you.
import java.util.ArrayList;
public class A6Q2 {
public static void main(String[] args) {
/* After building your GenericStack
from the ArrayList, add codes here to build the two Stacks
* (String and Integer) here
*/
GenericStack<String> fruits =
new GenericStack<String>();
fruits.push("apple");
fruits.push("mango");
fruits.push("banana");
System.out.println("Top of fruits
stack: " + fruits.peek());
System.out.println("Size of fruits
stack: " + fruits.size());
System.out.println("Popped " +
fruits.pop());
System.out.println("Fruits stack
contents: " + fruits);
System.out.println("-------");
GenericStack<Integer> nums =
new GenericStack<Integer>();
nums.push(2);
nums.push(3);
nums.push(4);
System.out.println("Top of number
stack: " + nums.peek());
System.out.println("Size of number
stack: " + nums.size());
System.out.println("Popped " +
nums.pop());
System.out.println("Number stack
contents: " + nums);
}
// Build a static class GenericStack<E> extends ArrayList
static class GenericStack<E> extends
ArrayList<E> {
public E peek() {
return
get(size()-1);
}
public void push(E o) {
add(o);
}
public E pop() {
return
remove(size() - 1);
}
@Override
public String toString() {
String s =
"stack: ";
for(int i =
size()-1; i >= 0; i--) {
if(i != size() - 1)
s += ", ";
s += get(i);
}
return s;
}
}
}
output
----
Top of fruits stack: banana
Size of fruits stack: 3
Popped banana
Fruits stack contents: stack: mango, apple
-------
Top of number stack: 4
Size of number stack: 3
Popped 4
Number stack contents: stack: 3, 2