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 ... ?
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;
}
This is an ArrayList implementation of a Stack, Where size is not a problem we can extend the stack as much as we want. Let's write a program to demonstrate implementation of Stack using ArrayList.
The array has a fixed size. The stack can contain elements of different data types. The array contains elements of the same data type. There are limited number of operations can be performed on a stack: push, pop, peek, etc.
Stack is a Collection, you can use ArrayList(Collection) constructor
list = new ArrayList(stack);
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, 3 you would expect in the list 3, 2, 1 because 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
Collections.reverse (stackToList);
This will reverse the list inline and give you 3, 2, 1
The above answer is not right, as the order will be reverse.
Instead you can just iterate like this:
Stack<State> stack = new Stack<>();
List<State> list = new ArrayList<>();
while(!stack.isEmpty()) {
list.add(stack.pop());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With