WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Scala - Arrays


The arrays provided in the Scala language are used to store fixed-size elements of the same type. Arrays are one of the most important data structures for each language.

Declaring array variables does not declare number0, number1, ..., number99 as separate variables, but declares a variable like numbers, then uses numbers[0], numbers[1],... , numbers[99] to represent a single variable. A specified element in the array is accessed through an index.

The index of the first element of the array is 0, and the index of the last element is the total number of elements minus 1.


Declare array

The following is the syntax for Scala array declarations:

var z:Array[String] = new Array[String](3)

or 

var z = new Array[String](3)

In the above syntax, z declares an array of string types with an array length of 3 and can store 3 elements. We can set values ​​for each element and access each element through the index as follows:

z(0) = "Welookups"; z(1) = "Baidu"; z(4/< Span class="lit">2) =  "Google"

The index of the last element uses the expression 4/2 as an index, similar to z(2) = "Google".

We can also define an array using the following methods:

var z = Array("Welookups ", "Baidu", "Google")

The image below shows an array of length myList with index values ​​from 0 to 9:


Processing arrays

The element type of the array and the size of the array are all deterministic, so when dealing with array elements, we usually use the basic for loop.

The following example demonstrates the creation, initialization, and other processing of arrays:

object Test {
   def main(args: Array[String]) {
      var myList = Array(1.9, 2.9, 3.4, 3.5)
      
      // Output all array elements
      for ( x <- myList ) {
         println( x )
      }

      // Calculate the sum of all the elements of the array
      var total = 0.0;
      for ( i <- 0 to (myList.length - 1)) {
         total += myList(i);
      }
      println("The sum is " + total);

      // Find the largest element in the array
      var max = myList(0);
      for ( i <- 1 to (myList.length - 1) ) {
         if (myList(i) > max) max = myList(i);
      }
      println("The maximum value is " + max);
    
   }
}

Execute the above code, the output is:

$ scalac Test.scala
$ scala Test
1.9
2.9
3.4
3.5
The sum is 11.7
The maximum is  3.5

Multidimensional array

Multidimensional arrays The value in one array can be another array, and the value of another array can be an array. Matrices and tables are our common two-dimensional arrays.

The above is an example of defining a two-dimensional array:

var myMatrix = ofDim[Int](3,3)

The array in the instance contains three array elements, each of which contains three values.

Next, let's look at a complete example of a two-dimensional array processing.:

import Array._

object Test {
   def main(args: Array[String]) {
      var myMatrix = ofDim[Int](3,3)
      
      // Creating a matrix
      for (i <- 0 to 2) {
         for ( j <- 0 to 2) {
            myMatrix(i)(j) = j;
         }
      }
      
      // Print two-dimensional array
      for (i <- 0 to 2) {
         for ( j <- 0 to 2) {
            print(" " + myMatrix(i)(j));
         }
         println();
      }
    
   }
}

Execute the above code, the output is:

$ scalac Test.scala
$ scala Test
0 1 2
0 1 2
0 1 2

Merge arrays

In the following example, we use the concat() method to merge two arrays, and the concat() method accepts multiple array parameters:

import Array._

object Test {
   def main(args: Array[String]) {
      var myList1 = Array(1.9, 2.9, 3.4, 3.5)
      var myList2 = Array(8.9, 7.9, 0.4, 1.5)

      var myList3 =  concat( myList1, myList2)
      
      // Output all array elements
      for ( x <- myList3 ) {
         println( x )
      }
   }
}

Execute the above code, the output is:

$ scalac Test.scala
$ scala Test
1.9
2.9
3.4
3.5
8.9
7.9
0.4
1.5

Create an interval array

In the following example, we used the range() method to generate an array within a range. The last parameter of the range() method is the step size. The default is 1:

import Array._

object Test {
   def main(args: Array[String]) {
      var myList1 = range(10, 20, 2)
      var myList2 = range(10,20)

      // Output all array elements
      for ( x <- myList1 ) {
         print( " " + x )
      }
      println()
      for ( x <- myList2 ) {
         print( " " + x )
      }
   }
}

Execute the above code, the output is:

$ scalac Test.scala
$ scala Test
10 12 14 16 18
10 11 12 13 14 15 16 17 18 19

Scala array method

The following table shows the important ways to handle arrays in the Scala language. Before using it, we need to introduce the package using import Array._.

serial number method and description
1

def apply( x: T, xs: T* ): Array[T]

Create an array of the specified object T, the value of T can be Unit, Double, Float, Long, Int, Char, Short, Byte, Boolean.

2

def concat[T]( xss: Array[T]* ): Array[T]

Merge arrays

3

def copy( src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int ): Unit

Copy an array to another array. Equivalent to Java's System.arraycopy(src, srcPos, dest, destPos, length).

4

def empty[T]: Array[T]

Return an array of length 0

5

def iterate[T]( start: T, len: Int )( f: (T) => T ): Array[T]

returns an array of the specified length, each array element being the return value of the specified function.

The above instance array has an initial value of 0 and a length of 3. The calculation function isa=>a+1

scala> Array.iterate(0,3)(a=>a+1)
res1: Array[Int] = Array(0, 1, 2)
6

def fill[T]( n: Int )(elem: => T): Array[T]

returns an array with the length specified for the first parameter and each element is padded with the second parameter.

7

def fill[T]( n1: Int, n2: Int )( elem: => T ): Array[Array[T]]

returns two arrays, the length is specified for the first argument, and each element is padded with the second argument.

8

def ofDim[T]( n1: Int ): Array[T]

Create an array of the specified length

9

def ofDim[T]( n1: Int, n2: Int ): Array[Array[T]]

Create a two-dimensional array

10

def ofDim[T]( n1: Int, n2: Int, n3: Int ): Array[Array[Array[T]]]

Create a three-dimensional array

11

def range( start: Int, end: Int, step: Int ): Array[Int]

Create an array within the specified interval, step is the step size between each element

12

def range( start: Int, end: Int ): Array[Int]

Create an array within the specified interval

13

def tabulate[T]( n: Int )(f: (Int)=> T): Array[T]

Returns an array of the specified length, each array element is the return value of the specified function, starting with 0 by default.

The above example returns 3 elements:

scala> Array.tabulate(3)(a => a + 5)
res0: Array[Int] = Array(5, 6, 7)
14

def tabulate[T]( n1: Int, n2: Int )( f: (Int, Int ) => T): Array[Array[T]]

Returns a two-dimensional array of the specified length, each array element being the return value of the specified function, starting with 0 by default.