If I have a stack using the mutable scala stack collection, is there a way I can copy the stack so that I can analyze its elements by popping it without altering the original stack? For instance, suppose I have a stack and code as follows:
import scala.collection.mutable.Stack
var stack1 = new Stack[Int]
/** Code that pushes integers on stack1*/
var stackCopy = stack1
while (!stackCopy.isEmpty) {
println(stackCopy.pop)
}
I want to use a while loop to print all elements in stack1. But when I make a copy and pop off that copy, the original stack (i.e. stack1) is also altered. I want to preserve the original stack, so how can I just get the contents, not the address?
You could use for comprehension:
or simply call the
foreachmethod:If you insist using a
whileloop, you can convert it to a list first:With all these methods, the original stack will be preserved.