如何为ArrayStack实现toString()方法?

时间:2015-04-17 09:12:12

标签: java data-structures stack tostring displayobject

我想显示ArrayQueue <Order>类型的订单列表  班级Order有一个ArrayStack<String>作为其属性之一。我覆盖了类toString()中的Order方法,但如何在ArrayStack类中覆盖它?因为这是我显示时得到的输出:

OrderNumber名称日期 ArrayStack @ 481adc30

我需要做什么才能正确显示ArrayStack中的字符串?我是否对ArrayStack类进行更改或更改Display方法中的内容?

这是我的显示方法:

 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类:

 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 */

订单类:

   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 个答案:

答案 0 :(得分:1)

override toString()中的ArrayStack方法如here所示。这将解决您的问题。

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

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

    return result;
}

答案 1 :(得分:0)

可能你应该这样做:

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

答案 2 :(得分:0)

使用此:

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