How do I implement the toString() method for an ArrayStack?

helloworld picture helloworld · Apr 17, 2015 · Viewed 9.5k times · Source

I want to display a list of orders of type ArrayQueue <Order> The class Order has an ArrayStack<String> as one of its attributes. I overrode the toString() method in the class Order, but how do I override it in the ArrayStack class? Because this is the output I get when I display:

OrderNumber Name Date ArrayStack@481adc30

What would I have to do to display the Strings in ArrayStack correctly? Do I make changes to class ArrayStack or change something in my Display method?

This is my Display method:

 public void display(){
    if (!isEmpty())
    for (int i = 0; i < numberOfEntries; i++) {
        System.out.println(queue[(frontIndex + i) % queue.length]);
    }
    else System.out.println("You don't have any orders");
    }

ArrayStack Class:

 public class ArrayStack < T > implements StackInterface < T >
{
    private T [] stack; // array of stack entries

    private int topIndex; // index of top entry

    private static final int DEFAULT_INITIAL_CAPACITY = 50;

    public ArrayStack ()
    {
        this (DEFAULT_INITIAL_CAPACITY);
    } // end default constructor


    public ArrayStack (int initialCapacity)
    {
        // the cast is safe because the new array contains null entries
        @ SuppressWarnings ("unchecked")
            T [] tempStack = (T []) new Object [initialCapacity];
        stack = tempStack;
        topIndex = -1;
    } // end constructor

    /*  Implementations of the stack operations */

Order Class:

   import java.util.Date;


public class Order {

    int orderNumber;
    String customerName;
    Date date;
    StackInterface <String> items;

Order( int number, String name, Date datum, StackInterface<String> item){
    orderNumber = number;
    customerName= name;
    date= datum;
    items = item;   
}

/Overriding toString() to Display a list of Orders as one String line. 
public String toString(){
    return orderNumber + " " + customerName + " " + date + " " + items;
}

Answer

Naman Gala picture Naman Gala · Apr 17, 2015

You can override toString() method in ArrayStack as shown here. This will solve your problem.

public String toString() {
    String result = "";

    for (int scan = 0; scan < top; scan++)
        result = result + stack[scan].toString() + "\n";

    return result;
}