Scala array
Fixed-length arrays
Declares the basic format of an array:
Val arr = new Array[t] (N)
Cases:
Val nums = new Array[int] (10)
Val STRs = new Array[string] (10)
When an array declaration is not given a value, it is initialized and can be assigned to the member of the group after initialization.
Array member initialization, such as type int, is initialized to NULL for the 0,string type.
Assigning a value directly to an array
Basic format:
Val arr = Array (x1,x2,.... xn);
Cases:
val s = Array ("Hello", "World")
Accessing array elements
Use () instead of [] to access the element.
Assigning a value to an array element
S (1) = "Scala"
Variable-length arrays
Using variable-length arrays requires the introduction of packages:
Import Scala.collection.mutable.ArrayBuffer
Declares an empty array cache, at which point B is an all-empty array with an array length of 0.
Val B = Arraybuffer[int] ()
Adds an element "1" to the tail of the array.
B+=1
Adds a series of elements "2,3" at the end of the array.
b+= (2,3)
Adds an array of elements (5,8,13,21) to the tail of the B array.
B++=array (5,8,13,21)
Removing the last 3 elements
B.trimend (3)
Inserts an element before the element with the mark bit 2.
B.insert (2,-2)
Inserts a series of elements before the element that marks bit 2.
B.insert (2,-3,-5)
Removes an element with a mark bit of 3.
B.remove (3)
Removes 2 elements by removing the element with the mark bit 1 and beyond.
B.remove (ON)
Converts the variable-length array to a fixed-length array.
Val C = B.toarray
Convert a fixed-length array to a variable-length array
Val d = C.tobuffer
Iterating through an array
Iterate by array ordinal.
for (i <-0 until a.length) {
println (i+ ":" +a (i))
}
Iterate directly over the members of the array (this is a better practice)
For (i <-array) {
println (i)
}
Get members by iterating over the array's subscript
for (i <-0 to (c.length-1) {
println (C (i))
}
Traverse each of the two elements in one line
for (i <-0 to (c.length,2)) {
println (C (i))
}
Reverse traversal
For (i-<-(0 to C.length). Reverse) {
println (C (i))
}
By enumerating the array members with a For statement, you can implement a variety of array controls, such as adding 1 to the array members and generating a new array:
Val new=for (i <-C) yield i+1
This array generation corresponds to the original array type (fixed length/variable length)
Multidimensional arrays
Val matrix = array.ofdim[double] (3,4)//three rows, four rows
Val triangle = new Array[array[int]] (10)
for (i <-0 until Triangle.length)
Fixed-length arrays and variable-length arrays
The use of fixed-length arrays is more encouraged for Scala.
Scala Basics 03: Arrays