Need to use pushpop method stacks Design a generic class Col
*Need to use push-pop method (stacks)* Design a generic class, Collection, that stores a collection of Objects (in an array), along with the current size of the collection. Provide public methods isEmpty, makeEmpty, insert, remove, and isPresent. isPresent(x) returns true if and only if an Object that is equal to x (as defined by equals) is present in the collection. *Need to use push-pop method (stacks) to test the Collection class.
Solution
Hi, Please find my implementation.
I have used ArrayList(a kinf of array) o implement.
########## MyStack.java ##############
import java.util.ArrayList;
public class MyStack<E extends Comparable<E>>
{
private ArrayList<E> list = new ArrayList<E>();
public int getSize()
{
return list.size();
}
public E peek()
{
if(list.size() == 0){
System.out.println(\"Stack is empty\");
return null;
}
return list.get(getSize() - 1);
}
public void push(E o)
{
list.add(o);
}
public E pop()
{
if(list.size() == 0){
System.out.println(\"Stack is empty\");
return null;
}
E o = list.get(getSize() - 1);
list.remove(getSize() - 1);
return o;
}
public boolean isEmpty()
{
return list.isEmpty();
}
public boolean isPresent(E o){
return list.contains(o);
}
public void makeEmpty(){
list = new ArrayList<E>();
}
@Override
public String toString()
{
return \"stack: \" + list.toString();
}
}
############ MyStackTest.java #############
public class MyStackTest {
public static void main(String[] args) {
MyStack<Integer> stack = new MyStack<Integer>();
stack.push(23);
stack.push(43);
stack.push(33);
System.out.println(\"PEEK: \"+stack.peek());
System.out.println(\"POP: \"+stack.pop());
System.out.println(\"PEEK: \"+stack.peek());
System.out.println(\"Is 33 present: \"+stack.isPresent(33));
stack.push(54);
stack.push(67);
System.out.println(\"PEEK: \"+stack.peek());
System.out.println(\"POP: \"+stack.pop());
System.out.println(\"PEEK: \"+stack.peek());
System.out.println(\"Is 3 present: \"+stack.isPresent(3));
stack.makeEmpty();
System.out.println(\"POP: \"+stack.pop());
}
}
/*
Sample Output:
PEEK: 33
POP: 33
PEEK: 43
Is 33 present: false
PEEK: 67
POP: 67
PEEK: 54
Is 3 present: false
Stack is empty
POP: null
*/



