Search code examples
javastack

How do we pop one stack completely into another stack


I have this code:

for (int i = 0; i < StackA.capacity(); i++) {
    StackB.push(StackA.get(i));
}

but it's giving me this error:

Array index out of range: 0
    at java.base/java.util.Vector.get

Can anybody help me identify my mistake?


Solution

  • If what you're looking is how to add elements into stackB without removing the elements from atackA, then you could use an Iterator to traverse stackA and add its elements into stackB.

    //Adding elements within stackB without consuming stackA
    for (Iterator<Integer> it = stackA.iterator(); it.hasNext(); ) {
        stackB.push(it.next());
    }
    

    Otherwise, as it has been suggested in the comments, if consuming the elements within stackA is not a problem, you could simply iterate your first stack until it's empty and popping each element into stackB during every iteration.

    //Adding elements within stackB by consuming stackA
    while (!stackA.empty()) {
        stackB.push(stackA.pop());
    }