Stack to & # 8594; ArrayList Java

I did Stack and ArrayList to do the research. Actually, I want my stack to be replaced with an ArrayList, but how do I convert a Stack to an ArrayList? How does this happen with push, pop ...?

thanks

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; } 
+11
source share
2 answers

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

 list = new ArrayList(stack); 
+22
source

The answer above is incorrect, since the order will be reversed.
Instead, you can simply repeat this:

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

Source: https://habr.com/ru/post/981956/


All Articles