In: Computer Science
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.
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()); } }