Create a new class named GenericStack that specifies a type variable that provid
ID: 3877353 • Letter: C
Question
Create a new class named GenericStack that specifies a type variable that provide for generics.
Declare a linked list that will hold the elements in the stack. Then, use the linked list to implement the methods show above.
Open the GenericStacksApp class. Then, declare a generic stack at the beginning of the main method that will store String objects.
Add code to the main method that uses the push method to add at least hree items to the stack. After each item is added, display its value at the console (use a string literal to do this). Then, use the size method to return the number of items in the stack and display that value.
Use the peek method to retrn the first item and display that item, and use the size method to return the number of items again and display that value.
Use the pop method to return each items again and display that value. Use the pop method to return each item, displaying it as it's returned, and display the number of items one more time.
Result should be as below:
Push: Apples
Push: Oranges
Push: Bananas
The stack contains 3 items
Peek: Bananas
The stack contains 3 items
Pop: Bananas
Pop: Oranges
Pop: Apples
The stack contains 0 items
Explanation / Answer
As per your requirement the below one is solution please follow it
########################GenericStack.java ###########
import java.util.LinkedList;
public class GenericStack<T> {
// generic linked list
private LinkedList<T> stack;
// constructor
public GenericStack() {
stack = new LinkedList<T>();
}
// push: adding element at last
public void push(T element){
System.out.println("push: "+element);
stack.addLast(element);
}
// pop: removing and returning element from last
public T pop(){
if(stack.size() == 0)
return null;
return stack.removeLast();
}
// peek: returning last element
public T peek(){
if(stack.size() == 0)
return null;
return stack.getLast();
}
public int size(){
return stack.size();
}
}
########## Test Class #############
public class GenericStackTest {
public static void main(String[] args) {
GenericStack<String> stack = new GenericStack<>();
stack.push("Apple");
stack.push("Oranges");
stack.push("Bananas");
System.out.println("The stack contains "+stack.size()+" items");
System.out.println("Peak: "+stack.peek()+" The stack contains "+stack.size()+" items");
System.out.println("Pop: "+stack.pop());
System.out.println("Pop: "+stack.pop());
System.out.println("Pop: "+stack.pop());
System.out.println("The stack contains "+stack.size()+" items");
}
}
/*
Sample Output:
push: Apple
push: Oranges
push: Bananas
The stack contains 3 items
Peak: Bananas The stack contains 3 items
Pop: Bananas
Pop: Oranges
Pop: Apple
The stack contains 0 items
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.