How to implement toString () method for ArrayStack?

I want to display a list of orders of type ArrayQueue <Order>

 Class Order

has ArrayStack<String>

as one of its attributes. I tried the method toString()

in the class Order

, but how do I override it in the class ArrayStack

? Because this is the result I get when displayed:

Order number Name Date ArrayStack @ 481adc30

What do I need to do to correctly display the rows in the ArrayStack? Can I make changes to the ArrayStack class 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;
}

      

+3


source to share


3 answers


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;
}

      

+1


source


Maybe you should do this:



System.out.println(Arrays.toString(queue.toArray()));

      

0


source


Use this:

System.out.println(Arrays.toString(queue));

      

0


source







All Articles