Question

In: Computer Science

I was trying to implement a stack for my assignment. One of the method given is...

I was trying to implement a stack for my assignment. One of the method given is this: public T[] toArray(); I need help to implement this method. The class is a generic class. I am using ArrayList to implement my stack. ArrayList<T> stack is the data structure. I want to convert everything in the ArrayList to an array.
I am implementing the  public T[] toArray() interface given to me, so I can not use the JDK toArray method.

Solutions

Expert Solution

Here is the complete implementation of the Stack.java generic class using ArrayList<T> also implemented the toArray() method that returns the T[] type, also demonstrated below writing a driver method.

Let me know for any questions.

=============================================================================

import java.util.ArrayList;
import java.util.Random;

public class Stack<T> {

    private ArrayList<T> elements;

    public Stack() {
        elements = new ArrayList<T>();
    }


    public T[] toArray() {

        T[] array = (T[]) new Object[elements.size()];
        for (int i = 0; i < elements.size(); i++) {
            array[i] = elements.get(i);
        }

        return array;

    }

    public void push(T element) {
        elements.add(element);
    }

    public T pop() {
        if (elements.size() == 0) return null;
        T element = elements.get(elements.size() - 1);
        elements.remove(elements.size() - 1);
        return element;
    }

    public boolean isEmpty() {

        return elements.size() == 0;
    }

    public T peek(){
        if (elements.size() == 0) return null;
        T element = elements.get(elements.size() - 1);
        return element;
    }

    public static void main(String[] args) {

        Stack<Integer> numbers = new Stack<Integer>();
        Random random = new Random();
        for(int i=1;i<=5;i++)numbers.push(random.nextInt(10)+1);

        System.out.println("Convert elements to array");
        Object[] array = numbers.toArray();
        for(Object num:array) System.out.println(num);

        System.out.println("Pop out the elements");
        while (!numbers.isEmpty()) System.out.println(numbers.pop());
    }

}

Related Solutions

0. Introduction. In this assignment you will implement a stack as a Java class, using a...
0. Introduction. In this assignment you will implement a stack as a Java class, using a linked list of nodes. Unlike the stack discussed in the lectures, however, your stack will be designed to efficiently handle repeated pushes of the same element. This shows that there are often many different ways to design the same data structure, and that a data structure should be designed for an anticipated pattern of use. 1. Theory. The most obvious way to represent a...
This is my current code for a question that asks: "Implement the stack methods push(x) and...
This is my current code for a question that asks: "Implement the stack methods push(x) and pop() using two queues". It works well, other than I want it to work for data of type T, not just Int's. (EXCUSE THE INDENTING... CHEGG POSTING DOESNT ALLOW PROPER CODE TO BE UPLOADED... JUST COPY PASTE IT INTO ECLIPSE IDE, HIGHLIGHT ALL CODE, PRESS COMMAND+SHIFT+F AND SHOULD AUTO-FORMAT) MY QUESTION: How could one modify this code in order to take data of type...
I was trying to implement a simple binary search tree using this given class of bst...
I was trying to implement a simple binary search tree using this given class of bst in c++ public: BST(); ~BST(); void insertKey(int newKey); bool hasKey(int searchKey); std::vector<int> inOrder(); int getHeight(); however; i am still required to use another class for the nodes as a pointer and i need to manage memory leak. in main we should ask for the numbers we need to insert in the binary search tree and also let the user end it with a letter...
Suppose I am trying to guess the salary of one of my fellow professors who I...
Suppose I am trying to guess the salary of one of my fellow professors who I think is 40 years old, has been at xxuniversity for 5 years, and has 25 publications. I am provided with the following regression analysis results from several alternative models that predict salary (in CAD) from these variables, based on N=35 participants. Note: yrs = years. Model 1; R-squared = 0.578; Adjusted R-squared = 0.537 Coefficient Standard Error     t          p-value     Intercept 86248.19 10016.43   8.61  ...
Good Evening Guys, It was given an assignment in which I have to implement iava object...
Good Evening Guys, It was given an assignment in which I have to implement iava object oriented programing. What I'm saying is that I wrote a restaurant order program in java but the whole code is located in main. Now, they want me to implement diferent classes (super), constructors, accesors, mutators, methods, objects, inheritance, polymorfism, overloading, overring, interfaces, and exceptions. I already wrote my program which works perfectly, I do not know how to implement all this object oriented features...
I am trying to implement a search function for a binary search tree. I am trying...
I am trying to implement a search function for a binary search tree. I am trying to get the output to print each element preceding the the target of the search. For example, in the code when I search for 19, the output should be "5-8-9-18-20-19" Please only modify the search function and also please walk me through what I did wrong. I am trying to figure this out. Here is my code: #include<iostream> using namespace std; class node {...
Implement a stack using a single queue. In particular, you are given a queue Q that...
Implement a stack using a single queue. In particular, you are given a queue Q that provides the method Q.size() to return its size at any point and the standard methods of queues (i.e, Q.enqueue(x) and Q.dequeue()). The requirement is to use such methods of Q to implement two methods S.push(x) and S.pop() for a stack S. What are the running times of your methods? Kindly answer using python programming
In trying to apply my knowledge in the real world, I am trying to create a...
In trying to apply my knowledge in the real world, I am trying to create a realistic retirement schedule. However, I am running into difficulties using both a financial calculator as well as our equations from class in doing this. I am trying to do the following: plan a retirement schedule between the ages of 25 and 70, in which I would deposit 20% of my income each year. The income starts at 80,000 with an annual growth rate of...
Professor, In trying to apply my knowledge in the real world, I am trying to create...
Professor, In trying to apply my knowledge in the real world, I am trying to create a realistic retirement schedule. However, I am running into difficulties using both a financial calculator as well as our equations from class in doing this. I am trying to do the following: plan a retirement schedule between the ages of 22 and 68, in which I would deposit 25% of my income each year. The income starts at 80,000 with an annual growth rate...
Are you able to implement a stack using just one queue? If yes, please provide the...
Are you able to implement a stack using just one queue? If yes, please provide the pop(only) algorithm to simulate the stack operations with just one queue. If yes, please provide the pop(only) algorithm to simulate the stack operations with just one queue. If no, explain.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT