Java 打印出堆栈/队列的所有元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23799687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:14:26  来源:igfitidea点击:

Print out all elements of a stack/queue

javaprintingstackqueuetostring

提问by user2963286

I am trying to go through a stack and a queue and print out the Object's values. In my Object's class I have implemented a toString. My stack and queue classes use a linked list. I tried going through it with a for loop like an array first, obviously doesn't work. I know how to get the top but not all of them.

我试图通过一个堆栈和一个队列并打印出对象的值。在我的 Object 类中,我实现了一个 toString。我的堆栈和队列类使用链表。我尝试先用像数组这样的 for 循环来遍历它,显然不起作用。我知道如何获得顶峰,但不是全部。

for (i = 0; i <= 9; i++) {
System.out.println(storageA[i].toString());
}

storageA is my stack with fixed size of 10.

storageA 是我的堆栈,固定大小为 10。

采纳答案by Marco Borchert

Assuming you want to iterate over the complete list holding Objects of type E:

假设您要遍历包含 E 类型对象的完整列表:

for (E element : storageA) {
  System.out.println(element.toString());
}

If you really only want elements 0-9 (better validate storageA.size > 9, else you get an IndexOutOfBoundsException):

如果你真的只想要元素 0-9(最好验证 storageA.size > 9,否则你会得到一个 IndexOutOfBoundsException):

for (i = 0; i <= 9; i++) {
   System.out.println(storageA.get(i).toString());
}