java - 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??
解决方案
您可以使用whichArrays#toString
返回.string
specified array
@Override
public String toString () {
return "stack {" + "elements =" + Arrays.toString(elements) + ", top =" + top + '}';
}
以上 to String 方法以如下格式返回字符串:
stack {elements =[1, 2, 3], top =3}
推荐阅读
- laravel - 在 Laravel 和 Vue.js 项目中找不到 SASS 依赖项
- swift - 控制何时在 Swift 中完成不同数量的请求
- qt - 在 MVS 中注册 Qt 版本时出错
- flutter - Flutter Audio Recorder - 自动剪辑音频文件的结尾?
- amazon-web-services - 在 APIGateway 和自定义 Cloudfront 分发中设置请求主机标头
- r - 在R中使用for循环创建多个对象
- python - 根据条件修改numpy数组值的最佳方法
- python - 康达错误_sysconfigdata_x86_64_conda_linux_gnu
- mongodb - 无法从外部连接到在 docker 容器中运行的 mongodb 实例
- javascript - 如何在 JavaScript 中将 JSON 键保存为字符串