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

谢谢

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;
}

最佳答案

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

list = new ArrayList(stack);

09-11 09:46