Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack to --> ArrayList Java

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;
}
like image 558
maevy Avatar asked Feb 04 '15 05:02

maevy


People also ask

Can stack be implemented by an ArrayList?

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.

Why stack is better than 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.


3 Answers

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

list = new ArrayList(stack);
like image 186
Evgeniy Dorofeev Avatar answered Oct 10 '22 11:10

Evgeniy Dorofeev


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

like image 21
RodXander Avatar answered Oct 10 '22 09:10

RodXander


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()); 
}
like image 30
Pritam Banerjee Avatar answered Oct 10 '22 10:10

Pritam Banerjee