Implement a StackInt class. The class will perform the basic Stack operations bu
ID: 3570573 • Letter: I
Question
Implement a StackInt class. The class will perform the basic Stack operations but only for integer values. The StackInt does not have a fixed size and it should allow the user to easily add and remove elements. The basic operations for Stacks are as follows:
push(value) Pushes the given value onto the top of the stack
pop() Removes and returns the value at the top of the stack
isEmpty() Returns true if this stack contains no values
peek() Returns the value at the top of the stack without removing it
size() Returns the number of values in the stack
You will have to use the same function names and the same given attributes. You cannot change them. Carefully read the description of the functions to understand if a function has a void return or not. Provide a main client class showing how you tested the correctness of your class. You will have to handle any Exceptional cases and make sure your class is fully functional.
Explanation / Answer
package com.example;
import java.util.Stack;
public class StackInt {
Stack<Integer> stackInt=new Stack<>();
public void push(int ele)
{
stackInt.add(ele);
}
public int pop()
{
return stackInt.pop();
}
public boolean isEmpty()
{
return stackInt.isEmpty();
}
public int peek()
{
return stackInt.peek();
}
public int size()
{
return stackInt.size();
}
}
package com.example;
public class MainClient {
public static void main(String[] args) {
StackInt si=new StackInt();
si.push(16);
si.push(20);
si.push(10);
System.out.println("Size of stack is "+si.size());
System.out.println("Element at top is "+si.peek());
System.out.println("is stack empty "+si.isEmpty());
System.out.println("Element removed from stack is "+si.pop());
}
}
o/p:
Size of stack is 3
Element at top is 10
is stack empty false
Element removed from stack is 10
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.