The Stack.size
function in Scala returns the number of elements in a Stack
object. In short, this function is used to get the current size of the Stack
object.
The following illustration shows a visual representation of the Stack.size
function.
To use the
Stack.size
function, you must include the following module:
scala.collection.mutable.Stack
stack_name.size;
// where the stack_name is the name of the stack object
The Stack.size
function does not require any parameters.
This function returns the number of elements in the Stack
object.
The following code shows how to use the Stack.size
function.
import scala.collection.mutable.Stackobject Main extends App {var stack = Stack[Int]()stack.push(0);stack.push(2);stack.push(5);stack.push(3);stack.push(1);println("The following are the elements in the stack: " + stack);println("The following is the size of the stack: " + stack.size);}
The push()
method is first used to add values to the object stack
. The size()
method in line returns the number of elements in the object stack
.