首页 > 解决方案 > How to rewrite the toString method to display my stack?

问题描述

How can I rewrite the toString method on my stack to display it in output. I have the following code:

public class Stack {

    public int [] elements;
    public int top;

    public Stack (int e) {
        elements = new int [e];
        top = -1;
    }

    public void insert (int e) {
        if (! isFull ()) {
            top ++;
            elements [top] = e;
        }

    }

    public boolean isEmpty () {
        return top == -1;
    }

    public boolean isFull () {
        return this.top == this.elements.length - 1;
    }

    public int remove () {
        if (! isEmpty ()) {
            return elements [top--];
        }
        return 0;

    }

    public int size () {
        return this.elements.length;
    }
}

In this case I wanted to display my instantiated stack in class main

Using Stack from Java itself is already created a structure where the stacks are printed in the output as: [1, 2, 3] or [1] if it has only one value.

Inserting the toString:

    

@Override
    public String toString () {
        return "stack {" + "elements =" + elements + ", top =" + top + '}';
    }

Only the name of the class is left. I would like something that displays the array correctly Can someone help me??

标签: javastacktostring

解决方案


您可以使用whichArrays#toString返回.stringspecified array

   @Override
    public String toString () {
        return "stack {" + "elements =" + Arrays.toString(elements) + ", top =" + top + '}';
    }

以上 to String 方法以如下格式返回字符串:

stack {elements =[1, 2, 3], top =3}

推荐阅读