Chapter 3 array related operations in notes of quick learning scala Second Edition

Keywords: Scala Java

Fixed length array

Array of constant length, array of Scala:

val nums = new Array[Int](10)
//Array of type Int, length 10, initial value 0
nums(0)
//Array access with parentheses

Variable length array

Similar to ArrayList in Java, scala uses ArrayBuffer

    val emptyBuffer = ArrayBuffer[Int]()
    val arrayBuffer = new ArrayBuffer[Int]()

    arrayBuffer += 1
    println(arrayBuffer) // ArrayBuffer(1)

    arrayBuffer += (2,3,4)
    println(arrayBuffer) //ArrayBuffer(1, 2, 3, 4)

    arrayBuffer ++= Array(5, 6, 7, 8)
    println(arrayBuffer) //ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8)

    arrayBuffer.trimEnd(3)
    println(arrayBuffer) //ArrayBuffer(1, 2, 3, 4, 5)
    

Use toArray and toBuffer to convert between Array and ArrayBuffer

Traverse Array and ArrayBuffer

grammar

var a = (1, 2, 3, 4)
for(i <- 0 until a.length){
    println(a(i))
}

until is similar to to to, but excludes the last element. We can also implement the following function:

0 until a.length by 2

Starting from the end of the array, the traversal is written as follows:

0 until a.length by -1

In addition to 0 until a.length or 0 until a.length by -1, you can also use a.indexes or a.indexes.reverse.

In addition, similar to the enhanced for loop in Java, scala also has:

for(elem <- a){
    
}

Array transformation

Instead of modifying the original array, these transformations generate a new array

val a = Array(2,4,6)
val res1 = for(elem <- a) yield 2 * elem
// res1 is Array(4,8,12)
val res2 = for(elem <- a if elem > 5) yield elem / 2
// res2 is Array(3)

Common algorithms

sum:

Array(1,2,3,4).sum 
// 10

min and max

ArrayBuffer(1,3,5,2).max
// 5

sorted

val b = ArrayBuffer(1,7,2,9)
val bsorted = b.sorted
// ArrayBuffer(1,2,7,9)

sortWith provides a comparison function

val = bDesc = b.sortWith(_ > _)
// ArrayBuffer(9,7,2,1)

mkString

b.mkString(" ")
//1 7 2 9
b.mkString("<",",",">")
//<1,7,2,9>

Multidimensional array

To construct multidimensional arrays in scala, the ofDim method is used:

val matrix = Array.ofDim[Double](3,4)//Double array with three rows and four columns

matrix(1)(2)//Access method

Posted by jcombs_31 on Tue, 29 Oct 2019 14:56:23 -0700