As one of the most common data structures, arrays are familiar to everyone. I mainly introduce the use of Array in scala in this article.
The elements in the array are all of the same data type.
Arrays are also divided into fixed-length arrays and variable-length arrays in scala.
1. Fixed-length array
Fixed-length array : the array length is fixed and unchanged
Example:
val array1 = new Array[Int](10) //初始元素都为0的长度为10的Int类型数组
val array2 = new Array[String](10) //初始化元素为null的长度为10的String类型数组
2. Variable length array
Variable length array : The length of the array can be changed, in Scala is the ArrayBuffer data structure
Example:
import scala.collection.mutable.ArrayBuffer
val a = ArrayBuffer[Int]()
a += 100 //在数组末加入数据
a += (1,2,3,4)
a ++= Array(1,2,3)
println(a)
Some basic operations of variable arrays:
a.insert(1,1000) //在索引为1的位置插入1000
a.insert(2,3,4,5) //在索引为2的位置插入3,4,5 结果为ArrayBuffer(100, 1, 3, 4, 5, 2, 3, 4, 1, 2, 3)
a.trimEnd(3) //删除数组末尾的3个元素 结果为ArrayBuffer(100, 1, 2, 3, 4)
a.remove(1) //删除索引为1的元素 结果为ArrayBuffer(100, 2, 3, 4, 1, 2, 3)
a.remove(0,3) //删除索引0后的三个元素 结果为ArrayBuffer(3, 4, 1, 2, 3)
a.toArray //将可变数组转为固长数组
Some calculation operations of the array, such as summation, sorting, etc. ~
val b = Array(1,3,1,4,5,8,8)
val res = for(x <- b) yield 2 * x //将b中的元素循环取出乘以2后在存入新数组res
for (x <- b if x % 2 != 0) yield 2 * x //取出数组中的奇数乘以2
scala.util.Sorting.quickSort(b) //对定长数组快排
val b_sum = b.sum //数组元素求和
val c = ArrayBuffer(5,6,88,8,8)
val c_sorted = c.sorted //对c数组进行排序 ArrayBuffer(5, 6, 8, 8, 88)
println(c_sorted)
val c_mkString = c.mkString(" and ") //使用and连接元素 5 and 6 and 88 and 8 and 8
println(c_mkString)
3. Multidimensional array
Multi-dimensional array : similar to the definition in other languages such as Java, that is, the value in one array can be another array, and the value in another array can also be an array
Example:
val matrix = Array.ofDim[Double](3,4) //使用Array方法ofDim构造3行4列的数组
matrix(2)(1) = 11 //给第二行第一列的元素赋值
val matrix2 = new Array[Array[Int]](10) //构造一个有10个Int类型数组元素的数组