In Scala Stack class, the copyToArray() method is utilized in copying the elements of the stack to an Array.
Method Definition: def copyToArray[B >: A](xs: Array[B], start: Int, len: Int): Int
Parameters:
xs: It denotes the array where elements are copied.
start: It denotes the starting index for the copy to takes place. Its default value is 0.
len: It denotes the number of elements to copy. Its default value is the length of the set.Return Type: It returns the elements of the stack to an array.
Example #1:
// Scala program of copyToArray() // method // Import Stack import scala.collection.mutable._ // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a stack val s1 = Stack(1, 2, 3) // Print the stack println(s1) // Creating an array val arr: Array[Int] = Array(0, 0, 0, 0, 0) // Applying copyToArray method s1.copyToArray(arr) // Displays output println("Elements in the array: ") for(elem <- arr) print(elem + " ") } } |
Stack(1, 2, 3) Elements in the array: 1 2 3 0 0
Example #2:
// Scala program of copyToArray() // method // Import Stack import scala.collection.mutable._ // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a stack val s1 = Stack(1, 2, 3) // Print the stack println(s1) // Creating an array val arr: Array[Int] = Array(0, 0, 0, 0, 0) // Applying copyToArray method s1.copyToArray(arr, 1, 2) // Displays output println("Elements in the array: ") for(elem <- arr) print(elem + " ") } } |
Stack(1, 2, 3) Elements in the array: 0 1 2 0 0

