scala-数组
scala默认是不可变数组,若要用变长数组,需要导入包:import scala.collection.mutable.ArrayBuffer
scala> val arr1 = new Array[Int](8) // 用new调用的是一般类的方法,而没有使用new关键字定义的则是调用Array的静态方法
arr1: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0)
scala> val arr2 = new Array[String](8)
arr2: Array[String] = Array(null, null, null, null, null, null, null, null)
scala> println(arr1)
[I@489091bd
scala> println(arr1.toBuffer) //使用toBuffer关键字可以把数组对象的内容转换成ArrayBuffer中来显示
ArrayBuffer(0, 0, 0, 0, 0, 0, 0, 0)
scala> val arr3 = Array("java","scala","python")
arr3: Array[String] = Array(java, scala, python)
scala> println(arr2(0)) // 与java不一样,遍历不用[],使用圆括号取下标对应里面的值
null
scala> println(arr3(0))
java
scala> val arr3 = ArrayBuffer[Int]()// 默认是不可变,若想使用可变的,则需要导入包 import scala.collection.mutable.ArrayBuffer
^
error: not found: value ArrayBuffer
scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer
scala> val arr2 = ArrayBuffer[Int]()
arr2: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()
scala> arr2 += 1
res4: arr2.type = ArrayBuffer(1)
scala> arr2 += (2,3,4)
^
warning: method += in trait Growable is deprecated (since 2.13.0): Use `++=` (addAll) instead of varargs `+=`
res5: arr2.type = ArrayBuffer(1, 2, 3, 4)
scala> arr2 ++= Array(5,6)
res6: arr2.type = ArrayBuffer(1, 2, 3, 4, 5, 6)
scala> arr2 ++= ArrayBuffer(7,8)
res7: arr2.type = ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8)
scala> for(i <- arr2) println(i)
1
2
3
4
5
6
7
8
scala> for(i <- 0 until arr2.length) println(i)
0
1
2
3
4
5
6
7
scala> for(i <- 0 until arr2.length) println(i, arr2(i))
(0,1)
(1,2)
(2,3)
(3,4)
(4,5)
(5,6)
(6,7)
(7,8)
scala> for(i <- (0 until arr2.length).reverse) println(i, arr2(i))
(7,8)
(6,7)
(5,6)
(4,5)
(3,4)
(2,3)
(1,2)
(0,1)
scala> val res = for( i <- arr2) yield i * 10 // yield的关键字可以理解为, 将 i*10的结果放在一个集合上放入到 res中。
res: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(10, 20, 30, 40, 50, 60, 70, 80)
scala> res.sum
res15: Int = 360
scala> res.max
res16: Int = 80
scala> res.sorted
res17: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(10, 20, 30, 40, 50, 60, 70, 80)
scala> Array(3,6,1,2).sorted
res18: Array[Int] = Array(1, 2, 3, 6)