• 发表于 9个月前
• 阅读 1
• 收藏 0
• 评论 0

## 定长数组

//定义一个长为10 Int 类型数组
scala> var numArray = new Array[Int](10)
numArray: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

//定义一个长为10 String 类型数组
scala> var strArray = new Array[String](10)
strArray: Array[String] = Array(null, null, null, null, null, null, null, null, null, null)

// 数组赋值
scala> numArray(0)=1

scala> numArray(11)=1
java.lang.ArrayIndexOutOfBoundsException: 11
... 29 elided
//赋值报错

scala> numArray
res8: Array[Int] = Array(1, 0, 0, 0, 0, 0, 0, 0, 0, 0)
// 这说明 数组的长度不可变但是值是可变的

// 定义数组的同时进行赋值
scala> var strArrayinit= Array("erhuan","nolimit")
strArrayinit: Array[String] = Array(erhuan, nolimit)

## 变长数组

// 导入包
scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer

// 定义一个边长的Int 形Array
scala> var numArray = ArrayBuffer[Int]()
numArray: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()

// 在0处插入1
scala> numArray.insert(0,1)

scala> numArray
res14: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1)

// 在0处 插入 1，2，3
scala> numArray.insert(0,1,2,3)

scala> numArray
res16: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 1)

//从0处开始  删除1和数
scala> numArray.remove(0,1)

scala> numArray
res18: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(2, 3, 1)

// 转成定长数组
scala> numArray.toArray
res19: Array[Int] = Array(2, 3, 1)

// String 类型变长数组
scala> var strArray = ArrayBuffer[String]()
strArray: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer()

//末尾添加元素
scala> strArray+="erhuan"
res20: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer(erhuan)

// 添加集合
scala> strArray+=("is","a","man")
res21: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer(erhuan, is, a, man)

//添加任意集合
scala> strArray++=Array("tall","1.8")
res22: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer(erhuan, is, a, man, tall, 1.8)

// 删掉末尾2个元素
scala> strArray.trimEnd(2)
scala> strArray
res24: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer(erhuan, is, a, man)

// 从1处开始删掉三个
scala> strArray.remove(1,3)

scala> strArray
res27: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer(erhuan)

// 转成定长
scala> strArray.toArray
res25: Array[String] = Array(erhuan)

×