Fixed length array

In Scala, if you need an Array of constant length, you use Array. But note the following two points:

  • Used in Scala(index)Rather than[index]To access elements in an array, because accessing elements, in Scala, is a method call,(index)It’s almost executed.apply(index)Methods.
  • Arrays in Scala are equivalent to arrays in Java,Array[Int]()This is equivalent to Java at the virtual machine levelint[].
// An array of 10 integers, all initialized to 0
scala> val nums=new Array[Int](10)
nums: Array[Int] = Array(0.0.0.0.0.0.0.0.0.0)

// An array of 10 elements, all initialized to NULL
scala> val strings=new Array[String](10)
strings: Array[String] = Array(null.null.null.null.null.null.null.null.null.null)

// Initialize with the specified value. No new keyword is required
scala> val a=Array("hello"."scala")
a: Array[String] = Array(hello, scala)

// Use () to access elements
scala> a(0)
res3: String = hello
Copy the code

Variable length arrays

Variable-length arrays (also known as buffer arrays) are implemented in Scala with an ArrayBuffer. When you build an ArrayBuffer, you have to give the type parameters, but you don’t have to specify the length, because the ArrayBuffer automatically expands and shrinks as needed. Variable-length arrays are built as follows:

import scala.collection.mutable.ArrayBuffer

object ScalaApp {
    
  // Equivalent to the Java main method
  def main(args: Array[String]): Unit = {
    // 1. Declare variable length arrays (buffer arrays)
    val ab = new ArrayBuffer[Int]()
    // 2. Add elements at the end
    ab += 1
    // 3. Add multiple elements at the end
    ab += (2.3.4)
    // 4. You can append any collection with ++=
    ab ++= Array(5.6.7)
    // 5. The buffer array can be printed directly
    println(ab)
    // remove the last three elements
    ab.trimEnd(3)
    // 7. Insert more elements after the first element
    ab.insert(1.8.9)
    // 8. Remove three elements starting with the second element. Default is 1 if no second argument is specified
    ab.remove(2.3)
    // 9. Convert buffer array to fixed-length array
    val abToA = ab.toArray
    // 10. The fixed-length array is printed as its hashCode value
    println(abToA)
    // 11. Convert fixed-length arrays to buffered arrays
    val aToAb = abToA.toBuffer
  }
}
Copy the code

Note that inserting elements at the end with += is an efficient operation with O(1) time complexity. The time complexity of randomly inserting elements using INSERT is O(n), and random insertion of elements in an ArrayBuffer is an inefficient operation because all elements after the insertion position are moved back accordingly.

Array traversal

object ScalaApp extends App {

  val a = Array(1.2.3.4.5.6.7.8.9.10)

  // 1. Approach one is equivalent to the enhanced for loop in Java
  for (elem <- a) {
    print(elem)
  }

  // 2
  for (index <- 0 until a.length) {
    print(a(index))
  }

  // 3. Method 3 is short for the second method
  for (index <- a.indices) {
    print(a(index))
  }

  // 4. Reverse traverse
  for (index <- a.indices.reverse) {
    print(a(index))
  }

}
Copy the code

Instead of writing the code in the main method, we inherit it from App.scala, which is a shorthand provided by Scala. Writing the code in the class is equivalent to writing it in the main method and simply running the class.

4. Array conversion

Array conversion is the creation of a new array from an existing array. If you have an array of A and want to multiply the even elements of a by 10 to create a new array, you can do it in either of the following ways:

object ScalaApp extends App {

  val a = Array(1.2.3.4.5.6.7.8.9.10)

  // 1. Yield keyword
  val ints1 = for (elem <- a if elem % 2= =0) yield 10 * elem
  for (elem <- ints1) {
    println(elem)
  }

  // 2. Approach 2 uses functional programming, which is similar to functional programming in Java 8, where each element is underlined
  val ints2 = a.filter(_ % 2= =0).map(_ * 10)
  for (elem <- ints1) {
    println(elem)
  }
}
Copy the code

Multidimensional arrays

As in Java, multidimensional arrays consist of single-dimensional arrays.

object ScalaApp extends App {

  val matrix = Array(Array(11.12.13.14.15.16.17.18.19.20),
    Array(21.22.23.24.25.26.27.28.29.30),
    Array(31.32.33.34.35.36.37.38.39.40))


  for (elem <- matrix) {

    for (elem <- elem) {
      print(elem + "-")} println()}}11-12-13-14-15-16-17-18-19-20-
21-22-23-24-25-26-27-28-29-30-
31-32-33-34-35-36-37-38-39-40-
Copy the code

Interoperability with Java

Since Scala arrays are implemented using Java arrays, they can be converted to each other.

import java.util

import scala.collection.mutable.ArrayBuffer
import scala.collection.{JavaConverters, mutable}

object ScalaApp extends App {

  val element = ArrayBuffer("hadoop"."spark"."storm")
  / / Scala Java
  val javaList: util.List[String] = JavaConverters.bufferAsJavaList(element)
  / / Java to Scala
  val scalaBuffer: mutable.Buffer[String] = JavaConverters.asScalaBuffer(javaList)
  for (elem <- scalaBuffer) {
    println(elem)
  }
}
Copy the code

The resources

  1. Martin Odersky. Scala Programming (3rd edition)[M]. Publishing House of Electronics Industry. 2018-1-1
  2. Kay S. Horstman. Learn Scala quickly (2nd edition)[M]. Publishing House of Electronics Industry. 2017-7