Java 将堆栈复制到数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20959537/
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
Copy stack to array
提问by user473973
This is a version of the algorithm I have:
这是我拥有的算法的一个版本:
public void copyStackToArray(Stack<Integer> stack) {
int i = 0;
while (!this.bestRouteStack.empty()) {
this.array[i++] = stack.pop();
}
}
(the bounds on the array are guaranteed to be okay here for my code)
(对于我的代码,数组的边界在这里保证没问题)
I'm wondering if there is a library algorithm that does this, but a search turned up nothing.
我想知道是否有一个库算法可以做到这一点,但搜索结果一无所获。
回答by Todd
Stack subclasses Vector which already supports this, try this...
堆栈子类 Vector 已经支持这个,试试这个......
stack.toArray(array)
回答by Ricket
I found that when I used the toArray
method, I got the results in the reverse order to what I expected. When I created this stack:
我发现当我使用该toArray
方法时,我得到的结果与我预期的相反。当我创建这个堆栈时:
Stack<String> stack = new Stack<>();
stack.push("foo");
stack.push("bar");
I wanted an array like:
我想要一个像这样的数组:
{"bar", "foo"}
Because of course, stacks are LIFO. If you pop each element off the stack, you would pop "bar" first, and then "foo".
因为当然,堆栈是 LIFO。如果从堆栈中弹出每个元素,则首先弹出“bar”,然后弹出“foo”。
Instead, toArray
returns {"foo", "bar"}
.
相反,toArray
返回{"foo", "bar"}
.
A solution is to use a LinkedList
instead. There is a push
method on LinkedList, it performs the same as addFirst
, and the result will be a list whose contents (if you traverse it of course) are "bar" and then "foo". And it also has the toArray
method which returns as expected.
一个解决方案是使用 aLinkedList
代替。push
LinkedList 上有一个方法,它的作用与 相同addFirst
,结果将是一个列表,其内容(当然如果你遍历它)是“bar”然后是“foo”。并且它还具有toArray
按预期返回的方法。
Test case:
测试用例:
LinkedList<String> list = new LinkedList<>();
list.push("foo");
list.push("bar");
String[] arr = list.toArray(new String[0]);
Assert.assertArrayEquals(new String[] { "bar", "foo" }, arr);