数组有两种类型:
-
Array:长度固定;
-
ArrayBuffer:长度可变。
创建数组常用方式
scala> val a = Array(1, 2, 3.4, "Hi")
a: Array[Any] = Array(1, 2, 3.4, Hi)
scala> val a = Array(1, 2, 3, 4, 5)
a: Array[Int] = Array(1, 2, 3, 4, 5)
scala> val a = new Array[String](3)
a: Array[String] = Array(null, null, null)
变长数组
Java的ArrayList的Scala对应物:ArrayBuffer。
scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer
scala> val a = ArrayBuffer(1, 2, 3.4, "Hi")
a: scala.collection.mutable.ArrayBuffer[Any] = ArrayBuffer(1, 2, 3.4, Hi)
scala> a += "Hello"
res0: a.type = ArrayBuffer(1, 2, 3.4, Hi, Hello)
scala> a += (10, 20, 30, "Nice", 30.0)
res1: a.type = ArrayBuffer(1, 2, 3.4, Hi, Hello, 10, 20, 30, Nice, 30.0)
scala> a ++= Array(100, "New Array")
res2: a.type = ArrayBuffer(1, 2, 3.4, Hi, Hello, 10, 20, 30, Nice, 30.0, 100, New Array)
scala> val b = a.toArray
b: Array[Any] = Array(1, 2, 3.4, Hi, Hello, 10, 20, 30, Nice, 30.0, 100, New Array)
scala> val a = b.toBuffer
a: scala.collection.mutable.Buffer[Any] = ArrayBuffer(1, 2, 3.4, Hi, Hello, 10, 20, 30, Nice, 30.0, 100, New Array)
scala> a.insert(2, "Ins")
scala> a
res4: scala.collection.mutable.Buffer[Any] = ArrayBuffer(1, 2, Ins, 3.4, Hi, Hello, 10, 20, 30, Nice, 30.0, 100, New Array)
scala> a.insert(2, "I", "n", "s")
scala> a
res6: scala.collection.mutable.Buffer[Any] = ArrayBuffer(1, 2, I, n, s, Ins, 3.4, Hi, Hello, 10, 20, 30, Nice, 30.0, 100, New Array)
scala> a.remove(2, 4)
scala> a
res8: scala.collection.mutable.Buffer[Any] = ArrayBuffer(1, 2, 3.4, Hi, Hello, 10, 20, 30, Nice, 30.0, 100, New Array)
阅读(3772) | 评论(0) | 转发(0) |