scala的集合对于java来说是更加面向对象

主要分为数组,list,set,map,tuple来讲解。其中还分为可变与不可变
且以常用的方法:CRUD来讲解,还有一个是合并

1.不可变数组

object Test02_Array extends App {
//访问不变数组
val array = new Array[Int](4)
val array2 = Array(1,2,4,5,6)
//1
for (elem <- 0 until array2.length) println(array2(elem))
//2
for (elem <- array2.indices) println(array2(elem))
//3
for (item <- array) println(item)
//4
val iter = array2.iterator
while (iter.hasNext){
println(iter.next())
}
//5
array2.foreach(println)
//6
array2.foreach((elem:Int)=>println(elem))
//7
println(array2.mkString(","))
}
//添加元素,传入的为新的数组
object Test1 extends App{
val arr1 = Array(1,2,3,4)
val arr2 = arr1.:+(5)
println(arr2.mkString("."))

val arr3 = arr2.+:(0)
println(arr3.mkString("."))

val arr4 = -1 +: arr3 :+ 6
println(arr4.mkString("."))
}

这里的数组的访问也是所有集合的访问方法。
scala之所以是函数式编程语言,就是因为把函数作为一等公民,函数也可以简化。
所有访问数组以及集合的方法中最简单的就是

  array2.foreach(println)

2.可变数组

import scala.collection.mutable.ArrayBuffer

object Test03_ArrayBuffer extends App {
//可变数组
//不传参数的话默认为16的空间
val arr1:ArrayBuffer[Int] = new ArrayBuffer[Int]()
val arr2 = ArrayBuffer(23, 44, 55)

for (elem <- arr2) println(elem)

}
object Test2 extends App{
val arr1 = ArrayBuffer(1,2,3,4)
println(arr1(3))
arr1 += 5
0 +=: arr1
println(arr1.mkString("."))
arr1.append(6)
arr1.prepend(-1)
println(arr1.mkString("."))
arr1.insert(1, 33)
println(arr1.mkString("."))
}

最后总结一下可变数组与不可变数组之间的转换

object Test22 extends App{
val arr = Array(1,2,3)
val arrayBuffer = arr.toBuffer
val newarr = arrayBuffer.toArray
}

3.多维数组

object Test04_MulArray extends App {
val arr:Array[Array[Int]] = Array.ofDim[Int](2, 3)

arr(0)(1) = 100
arr(1)(2) = 200

for (i<-0 until arr.length;j <- 0 until arr(i).length) {
print(arr(i)(j) + "\t")
if(j == arr(i).length - 1)
println()
}
arr.foreach(_.foreach(println))

}

多维数组调用的数组的方法Array.ofDim()

4.List不可变

object Test05_List01 extends App {
val list = List(1,2,3,4)
val list1 = 0 +: list :+ 5
list1.foreach(println)
//0放前面
val list2 = Nil.::(0)
//拼接
val list3 = -1 :: 0 :: Nil
list3.foreach(println)
//链表拼接
val list4 = list2 :: list3
println(list4)
val list5 = list2 ::: list3
println(list5)
val list6 = list2 ++ list3
println(list6)
}

5.ListBuffer可变List

import scala.collection.mutable.ListBuffer

object Test06_ListBuffer extends App {
val list = ListBuffer(1,2,3,4,5)
println(list)
list.append(6)
list.prepend(0)
println(list)
list.insert(1, 22)
println(list)
-1 +=: list += 7
println(list)
//合并list
val list1 = ListBuffer(-3,-2)
val newlist = list1 ++ list
println(newlist)
//修改
newlist(4) = 0
newlist.update(4, 1)
println(newlist)
//删除
newlist.remove(0)//索引
newlist -= -3 //元素值
println(newlist)

}