Question

Now, your objective is to rewrite the same Stack class with a Generic ArrayList and make...

Now, your objective is to rewrite the same Stack class with a Generic ArrayList and make the entire class support using Generic types. You should be able to create a Stack of any primitive wrapper class, and show us that your Generic Stack implementation (push, pop, search, display, etc.) works with: • Character (Stack) • Integer (Stack) • Float (Stack • Double (Stack) • String (Stack) You can create these Stack objects in main() and perform operations on them to show that they work as intended.

public class Stack implements Comparable<Stack>, Serializable {
  
   private static final long serialVersionUID = 1L;
  
   int[] stack;
   int top;
  
   transient int admin;
  
   public Stack(int n) {
       stack = new int[n];
       top = -1;
       admin = 42;
   }
  
   public Stack() {
       this(5);
   }
  
   public void push(int n) {
       if(top == 4) {
           System.out.println("Stack Overflow");
           return;
       }
      
       stack[++top] = n;
       System.out.println("Pushed " + n);
   }
  
   public int pop() {
       if(top == -1)
           System.out.println("Stack Underflow");
      
       return stack[top--];
   }
  
   public void display() {
       for(int i = 0; i <= top; i++)
           System.out.print(stack[i] + " ");
      
       System.out.println();
   }
  
   public void display(int start, int end) {
       if(start > top)
           return;
       if(end > top)
           end = top;
       for(int i = start; i <= end; i++)
           System.out.print(stack[i] + " ");
      
       System.out.println();
   }
  
   public void search(int n) {
       for(int i = 0; i <= top; i++)
           if(stack[i] == n) {
               System.out.println("Found at " + i);
               return;
           }
      
       System.out.println("Not found");
   }

   @Override
   public int compareTo(Stack o) {
       if(this.top < o.top)
           return -1;
       else if(this.top == o.top)
           return 0;
       else
           return 1;
   }
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please find the code below:

Stack.java

package classess6;

import java.io.Serializable;

public class Stack<T> implements Comparable<Stack>, Serializable {

   private static final long serialVersionUID = 1L;

   T[] stack;
   int top;

   transient int admin;

   public Stack(int n) {
       stack = (T[])new Object[n];
       top = -1;
       admin = 42;
   }

   public Stack() {
       this(5);
   }

   public void push(T n) {
       if(top == 4) {
           System.out.println("Stack Overflow");
           return;
       }

       stack[++top] = n;
       System.out.println("Pushed " + n);
   }

   public T pop() {
       if(top == -1)
           System.out.println("Stack Underflow");

       return stack[top--];
   }

   public void display() {
       for(int i = 0; i <= top; i++)
           System.out.print(stack[i] + " ");

       System.out.println();
   }

   public void display(int start, int end) {
       if(start > top)
           return;
       if(end > top)
           end = top;
       for(int i = start; i <= end; i++)
           System.out.print(stack[i] + " ");

       System.out.println();
   }

   public void search(T n) {
       for(int i = 0; i <= top; i++)
           if(stack[i] == n) {
               System.out.println("Found at " + i);
               return;
           }

       System.out.println("Not found");
   }

   @Override
   public int compareTo(Stack o) {
       if(this.top < o.top)
           return -1;
       else if(this.top == o.top)
           return 0;
       else
           return 1;
   }
}

Main.java

package classess6;

import java.util.Scanner;
import java.util.stream.LongStream;

public class Main {
   public static void main(String[] args) {
  
       Stack<Character> stack = new Stack<>();
       stack.push('L');
       stack.push('O');
       stack.push('V');
       stack.push('E');
      
       stack.display();
      
       System.out.println();
       Stack<Double> stack2 = new Stack<>();
       stack2.push(1.1);
       stack2.push(2.1);
       stack2.push(3.1);
       stack2.push(4.1);
       stack2.display();
      
   }
}

Add a comment
Know the answer?
Add Answer to:
Now, your objective is to rewrite the same Stack class with a Generic ArrayList and make...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,In...

    Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,Integer. Im not sure how to fix this. public class Evaluator { public static void evaluatePost(String postFix)    {        LinkedStack stack2 = new LinkedStack();        int val1;        int val2;        int result;        for(int i = 0; i < postFix.length(); i++)        {            char m = postFix.charAt(i);            if(Character.isDigit(m))            {                stack2.push(m);            }            else            {               ...

  • I have added a little Code but I need help with the rest. /** A class...

    I have added a little Code but I need help with the rest. /** A class of stacks whose entries are stored in a chain of nodes. Implement all methods in MyStack class Main Reference : text book or class notes Do not change or add data fields */ package PJ2; public class MyStack<T> implements StackInterface<T> {    // Data fields    private Node<T> topNode; // references the first node in the chain    private int numberOfEntries;       public...

  • how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 }...

    how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 } class Stack { Node head; int size; Stack() //default constructor { this.head=null; this.size=0; } //Input = data //Output = void (just adds value to list) // method pushes elements on stack // time: O(1) // space: O(1) public void push(int data) { Node node=new Node(data); node.next=head; head=node; size++; } //Input = none //Output = top of stack // method pops value from top of...

  • Need Help ASAP!! Below is my code and i am getting error in (public interface stack)...

    Need Help ASAP!! Below is my code and i am getting error in (public interface stack) and in StackImplementation class. Please help me fix it. Please provide a solution so i can fix the error. thank you.... package mazeGame; import java.io.*; import java.util.*; public class mazeGame {    static String[][]maze;    public static void main(String[] args)    {    maze=new String[30][30];    maze=fillArray("mazefile.txt");    }    public static String[][]fillArray(String file)    {    maze = new String[30][30];       try{...

  • (How do I remove the STATIC ArrayList from the public class Accounts, and move it to...

    (How do I remove the STATIC ArrayList from the public class Accounts, and move it to the MAIN?) import java.util.ArrayList; import java.util.Scanner; public class Accounts { static ArrayList<String> accounts = new ArrayList<>(); static Scanner scanner = new Scanner(System.in);    public static void main(String[] args) { Scanner scanner = new Scanner(System.in);    int option = 0; do { System.out.println("0->quit\n1->add\n2->overwirte\n3->remove\n4->display"); System.out.println("Enter your option"); option = scanner.nextInt(); if (option == 0) { break; } else if (option == 1) { add(); } else...

  • how would I complete this code without calling any built-in java collection framework classes like ArrayList,...

    how would I complete this code without calling any built-in java collection framework classes like ArrayList, LinkedList, etc? import java.util.Iterator; class CallStack<T> implements Iterable<T> { // You'll want some instance variables here public CallStack() { //setup what you need } public void push(T item) { //push an item onto the stack //you may assume the item is not null //O(1) } public T pop() { //pop an item off the stack //if there are no items on the stack, return...

  • stack.h template class Stack{ public: Stack(int max = 10); ~Stack() {delete [] stack;} bool isEmpty() const...

    stack.h template class Stack{ public: Stack(int max = 10); ~Stack() {delete [] stack;} bool isEmpty() const { return top == -1; } bool isFull() const { return top == MaxStackSize; } T peek() const; void push(const T& x); void pop(); private: int top; int MaxTop; T * stack; } source.cpp What is printed by the following program segment? Stack s; int n; s.push(4); s.push(6); s.push(8); while(!s.isEmpty()) { n = s.peek(); cout << n << ‘ ‘; s.pop(); } cout<< endl;...

  • I need to implement raw array Stack for create empty stack, isEmpty, isFull, push, pop, and...

    I need to implement raw array Stack for create empty stack, isEmpty, isFull, push, pop, and size using below pseudo code. I need two classes with stack pseudo code implementation and the main method to demonstrate the correct working of each operation. pseudo code StackADT (using raw array) class StackADT { int top int items[] int max StackADT(int n) Initialize array to n capacity top = 0 max = n boolean isEmpty() if array has no elements return true else...

  • I have a java project that I need help trying to finish. I have most of it completed but the issue I am running into is adding numbers with different lengths. Project requirements: . Use a Stack ADT w...

    I have a java project that I need help trying to finish. I have most of it completed but the issue I am running into is adding numbers with different lengths. Project requirements: . Use a Stack ADT with the implementation of your choice (Array or Link), it should not make a difference 2.Read two “integer” numbers from the user. Hint: You don’t need to use an int type when you read, it may be easier to parse the input...

  • Java - data structures Suppose that in the array-based stack, the array doubles in size after...

    Java - data structures Suppose that in the array-based stack, the array doubles in size after multiple push operations. But later on, fewer than half of the array’s locations might actually be used by the stack due to pop operations. Revise the implementation so that its array also can shrink in size as objects are removed from the stack. Accomplishing this task will require two new private methods, as follows: The first new method checks whether we should reduce the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT