堆栈到--> ArrayList Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28313917/
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-11-02 13:23:06  来源:igfitidea点击:

Stack to --> ArrayList Java

javaarrayliststack

提问by maevy

I made a Stack and an ArrayList to make a research. Actually I want now to make my Stack replaced by an ArrayList, but how to transform a Stack into an ArrayList ? How is it going with push, pop ... ?

我做了一个 Stack 和一个 ArrayList 来进行研究。实际上我现在想让我的 Stack 被一个 ArrayList 替换,但是如何将一个 Stack 转换为一个 ArrayList ?push, pop ... 进展如何?

Thank you

谢谢

public static ArrayList<State> search(State finalstate)
{
    ArrayList<State> toreturn = new ArrayList<State>();
    Stack<State>mystack=new Stack<State>();
    mystack.push(initState);
    State currState;
    currState=initState;
    while(!mystack.isEmpty() && !currState.equals(finalstate) )
    {
        currState=mystack.pop();
        toreturn.add(currState);
        if(currState.vecinos.containsKey("up"))
        {
            mystack.push(currState).vecinos.get("up");
        }
        if(currState.vecinos.containsKey("down"))
        {
            mystack.push(currState).vecinos.get("down");
        }
        if(currState.vecinos.containsKey("left"))
        {
            mystack.push(currState).vecinos.get("left");
        }
        if(currState.vecinos.containsKey("right"))
        {
            mystack.push(currState).vecinos.get("right");
        }
    }

    return toreturn;
}

回答by Evgeniy Dorofeev

Stack is a Collection, you can use ArrayList(Collection) constructor

Stack 是一个集合,可以使用 ArrayList(Collection) 构造函数

list = new ArrayList(stack);

回答by RodXander

The simplest way I've found to convert a Stack into a List is using the following line:

我发现将堆栈转换为列表的最简单方法是使用以下行:

List<Integer> stackToList = new ArrayList(stack);

However, this yields the stack reversed. Meaning, if your stack was 1, 2, 3you would expect in the list 3, 2, 1because that's the order the stack objects would be "popped". That's not the case though instead, you get 1, 2, 3. So, in order to get the expected output, you need to execute

但是,这会导致堆栈颠倒。意思是,如果您的堆栈是1, 2, 3,您会期望在列表3, 2, 1 中,因为这是堆栈对象将被“弹出”的顺序。但事实并非如此,您会得到1, 2, 3。所以,为了得到预期的输出,你需要执行

Collections.reverse (stackToList);

This will reverse the list inline and give you 3, 2, 1

这将内联反转列表并为您提供3, 2, 1

回答by Pritam Banerjee

The above answer is not right, as the order will be reverse.
Instead you can just iteratelike this:

上面的答案是不正确的,因为顺序会颠倒。
相反,您可以像这样迭代

Stack<State> stack = new Stack<>();
List<State> list = new ArrayList<>();
while(!stack.isEmpty()) { 
    list.add(stack.pop()); 
}