Multidimensional array is an array which store data in matrix form. You can create from two dimensional to three, four and many more dimensional array according to your need. Below we have mentioned array syntax. Scala provides an ofDim method to create multidimensional array.
Multidimensional Array Syntax
var arrayName = Array.ofDim[ArrayType](NoOfRows,NoOfColumns) or
var arrayName = Array(Array(element?), Array(element?), ?)
Scala Multidimensional Array Example by using ofDim
In This example, we have created array by using ofDim method.
class ArrayExample{
var arr = Array.ofDim[Int](2,2) // Creating multidimensional array
arr(1)(0) = 15 // Assigning value
def show(){
for(i<- 0 to 1){ // Traversing elements by using loop
for(j<- 0 to 1){
print(" "+arr(i)(j))
}
println()
}
println("Third Element = "+ arr(1)(1)) // Accessing elements by using index
}
}
object MainObject{
def main(args:Array[String]){
var a = new ArrayExample()
a.show()
}
}
Output:
0 0
15 0
Third Element = 0
Scala Multidimensional Array by using Array of Array
Apart from ofDim you can also create multidimensional array by using array of array. In this example, we have created multidimensional array by using array of array.
class ArrayExample{
var arr = Array(Array(1,2,3,4,5), Array(6,7,8,9,10)) // Creating multidimensional array
def show(){
for(i<- 0 to 1){ // Traversing elements using loop
for(j<- 0 to 4){
print(" "+arr(i)(j))
}
println()
}
}
}
object MainObject{
def main(args:Array[String]){
var a = new ArrayExample()
a.show()
}
}
Output:
1 2 3 4 5
6 7 8 9 10
Hope this helps!
If you need to know more about Scala, join Spark course today and become the expert.
Thanks!!