Scala Tutorial - Learn How To Use Scala's Mutable Array

By Nadim Bahadoor | Last updated: February 3, 2020 at 7:27 am

Overview

In this tutorial, we will learn how to use Scala's Mutable Array to perform common operations such as initialize an Array, access elements at specific index, create 2D or 3D dimensional Arrays, and copy Arrays.

 

And, don't forget to review the Data Structures tutorial before delving into Scala's Immutable and Mutable collections.

 

More advanced functions such as aggregate, fold, reduce, map, flatMap etc on the Mutable Array will be discussed in Chapter 8 on Collection Functions.

 

What is an Array?

As per Wikipedia, an Array is a mutable data structure of fixed length. It also allows you to access and modify elements at specific index.

 

Steps

1. How to initialize a String Array with 3 elements

The code below shows how to initialize a String Array with 3 elements.


println("Step 1: How to initialize a String Array with 3 elements")
val array1: Array[String] = Array("Plain Donut","Strawberry Donut","Chocolate Donut")
println(s"Elements of array1 = ${array1.mkString(", ")}")

You should see the following output when you run your Scala application in IntelliJ:


Step 1: How to initialize a String Array with 3 elements
Elements of array1 = Plain Donut, Strawberry Donut, Chocolate Donut

 

2. How to access elements at specific index in an Array

The code below shows how to access elements at specific index in an Array.


println("\nStep 2: How to access elements at specific index in an Array")
println(s"Element at index 0 = ${array1(0)}")
println(s"Element at index 1 = ${array1(1)}")
println(s"Element at index 2 = ${array1(2)}")

You should see the following output when you run your Scala application in IntelliJ:


Step 2: How to access elements at specific index in an Array
Element at index 0 = Plain Donut
Element at index 1 = Strawberry Donut
Element at index 2 = Chocolate Donut

3. How to initialize an Array by specifying it's capacity

The code below shows how to initialize an Array by specifying it's capacity.


println("\nStep 3: How to initialize an Array by specifying it's capacity")
val array2: Array[String] = new Array(3)
array2(0) = "Plain Donut"
array2(1) = "Strawberry Donut"
array2(2) = "Chocolate Donut"
println(s"Elements of array2 = ${array2.mkString(", ")}")

You should see the following output when you run your Scala application in IntelliJ:


Step 3: How to initialize an Array by specifying it's capacity
Elements of array2 = Plain Donut, Strawberry Donut, Chocolate Donut

 

4. How to create a 2D Array (2 dimension array)

The code below shows how to create a 2D Array (2 dimension array).


println("\nStep 4: How to create a 2D Array (2 dimension array)")
val rows = 2
val columns = 2
val array3: Array[Array[String]] = Array.ofDim[String](rows,columns)
array3(0)(0) = "Plain"
array3(0)(1) = "Donut"
array3(1)(0) = "Strawberry"
array3(1)(1) = "Donut"
println(s"Elements of 2 dimensional array = ${array3.deep.toList}")

You should see the following output when you run your Scala application in IntelliJ:

Step 4: How to create a 2D Array (2 dimension array)
Elements of 2 dimensional array = List(Array(Plain, Donut), Array(Strawberry, Donut))

 

5. How to create 3D Array (3 Dimension Array) using Array.ofDim() method

The code below shows how to create 3D Array (3 Dimension Array) using Array.ofDim() method.


println("\nStep 5: How to create 3D Array (3 Dimension Array) using Array.ofDim() method")
val array4: Array[Array[String]] = Array.ofDim[String](3,3)
println(s"Elements of 3 dimensional array = ${array4.deep.toList}")

You should see the following output when you run your Scala application in IntelliJ:

Step 5: How to create 3D Array (3 Dimension Array) using Array.ofDim() method
Elements of 3 dimensional array = List(Array(null, null, null), Array(null, null, null), Array(null, null, null))

 

6. How to create an Array using tabulate function

The code below shows how to create an Array using tabulate function.


println("\nStep 6: How to create an Array using tabulate function")
val array5: Array[Int] = Array.tabulate(5)(_ + 1)
println(s"Array of 5 columns = ${array5.toList}")

You should see the following output when you run your Scala application in IntelliJ:


Step 6: How to create an Array using tabulate function
Array of 5 columns = List(1, 2, 3, 4, 5)

 

7. How to create dimensional Arrays using tabulate function

The code below shows how to create dimensional Arrays using tabulate function.


println("\nStep 7: How to create dimensional Arrays using tabulate function")
val row1 = 1
val column3 = 3
val arrayOfOneRowAndThreeColumns = Array.tabulate(row1, column3)( (row, column) => row + column )
println(s"Array with 1 row and 3 columns = ${arrayOfOneRowAndThreeColumns.deep.toString}")

val row2 = 2
val arrayOfTowRowsAndThreeColumns = Array.tabulate(row2, column3)( (row, column) => row + column )
println(s"Array with 2 rows and 3 columns = ${arrayOfTowRowsAndThreeColumns.deep.toString}")

You should see the following output when you run your Scala application in IntelliJ:


Step 7: How to create dimensional Arrays using tabulate function
Array with 1 row and 3 columns = Array(Array(0, 1, 2))
Array with 2 rows and 3 columns = Array(Array(0, 1, 2), Array(1, 2, 3))

 

8. How to create Array using Range

The code below shows how to create Array using Range.


println("\nStep 8: How to create Array using Range")
val rangeArray: Array[Int] = (1 to 10).toArray[Int]
println(s"Array using Range from 1 to 10 = ${rangeArray.mkString(", ")}")

You should see the following output when you run your Scala application in IntelliJ:


Step 8: How to create Array using Range
Array using Range from 1 to 10 = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

 

9. How to copy an Array using Array.copy

The code below shows how to copy an Array using Array.copy.


println("\nStep 9: How to copy an Array using Array.copy")
val copyOfRangeArray: Array[Int] = new Array(rangeArray.size)
Array.copy(rangeArray, 0, copyOfRangeArray, 0, rangeArray.size)
println(s"copy of range array with elements from rangeArray = ${copyOfRangeArray.mkString(", ")}")

You should see the following output when you run your Scala application in IntelliJ:


Step 9: How to copy an Array using Array.copy
copy of range array with elements from rangeArray = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

 

10. How to clone an Array

The code below shows how to clone an Array.


println("\nStep 10: How to clone an Array")
val clonedRangeArray = rangeArray.clone
clonedRangeArray(0) = 10 // update index 0 to value 10
println(s"clonedRangeArray = ${clonedRangeArray.mkString(", ")}")
println(s"original range array still unchanged = ${rangeArray.mkString(", ")}")

You should see the following output when you run your Scala application in IntelliJ:


Step 10: How to clone an Array
clonedRangeArray = 10, 2, 3, 4, 5, 6, 7, 8, 9, 10
original range array still unchanged = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

 

11. How to iterate over an Array using for comprehension

The code below shows how to iterate over an Array using for comprehension.


println("\nStep 11: How to iterate over an Array using for comprehension")
for(d <- array1){
 println(s"d = $d")
}

You should see the following output when you run your Scala application in IntelliJ:


Step 11: How to iterate over an Array using for comprehension
d = Plain Donut
d = Strawberry Donut
d = Chocolate Donut

 

12. How to merge two Arrays using Array.concat

The code below shows how to merge two Arrays using Array.concat.


println("\nStep 12: How to merge two Arrays using Array.concat")
val moreDonutsArray: Array[String] = Array("Vanilla Donut","Glazed Donut")
val mergedDonutArray: Array[String] = Array.concat(array1, moreDonutsArray)
println(s"Merged Array of donuts = ${mergedDonutArray.mkString(", ")}")

You should see the following output when you run your Scala application in IntelliJ:


Step 12: How to merge two Arrays using Array.concat
Merged Array of donuts = Plain Donut, Strawberry Donut, Chocolate Donut, Vanilla Donut, Glazed Donut

 

13. How to check if two Arrays are equal

The code below shows how to check if two Arrays are equal.


println("\nStep 13: How to check if two Arrays are equal")
val arrayToCompare = Array[String]("Plain Donut","Strawberry Donut","Chocolate Donut")
 
println(s"using == ${array1 == moreDonutsArray}") // prints false

println(s"using == ${array1 == arrayToCompare}") // ALSO prints false ??? what ... be careful

println(s"using sameElement function = ${array1 sameElements arrayToCompare}") // NOW this works and returns true!

You should see the following output when you run your Scala application in IntelliJ:


Step 13: How to check if two Arrays are equal
using == false
using == false
using sameElement function = true

 

14. How to check if two Arrays are equal using deep function and == 

The code below shows how to check if two Arrays are equal using deep function and == .


println("\nStep 14: How to check if two Arrays are equal using deep function and == ")
println(s"using deep function = ${array1.deep == arrayToCompare.deep}")

You should see the following output when you run your Scala application in IntelliJ:


Step 14: How to check if two Arrays are equal using deep function and == 
using deep function = true

 

This concludes our tutorial on Learn How To Use Scala's Mutable Array and I hope you've found it useful!

 

Stay in touch via Facebook and Twitter for upcoming tutorials!

 

Don't forget to like and share this page :)

Summary

In this tutorial, we went over the following:

  • How to initialize a String Array with 3 elements
  • How to access elements at specific index in an Array
  • How to initialize an Array by specifying it's capacity
  • How to create a 2D Array (2 dimension array)
  • How to create 3D Array (3 Dimension Array) using Array.ofDim() method
  • How to create an Array using tabulate function
  • How to create dimensional Arrays using tabulate function
  • How to create Array using Range
  • How to copy an Array using Array.copy
  • How to clone an Array
  • How to iterate over an Array using for comprehension
  • How to merge two Arrays using Array.concat
  • How to check if two Arrays are equal
  • How to check if two Arrays are equal using deep function and ==

Tip

Source Code

The source code is available on the allaboutscala GitHub repository.

 

What's Next

In the next tutorial, I will show you how to use Scala's Mutable ArrayBuffer.

 

Nadim Bahadoor on FacebookNadim Bahadoor on GithubNadim Bahadoor on LinkedinNadim Bahadoor on Twitter
Nadim Bahadoor
Technology and Finance Consultant with over 14 years of hands-on experience building large scale systems in the Financial (Electronic Trading Platforms), Risk, Insurance and Life Science sectors. I am self-driven and passionate about Finance, Distributed Systems, Functional Programming, Big Data, Semantic Data (Graph) and Machine Learning.
Other allaboutscala.com tutorials you may like: