創(chuàng)建list
var list1 = List(1,2,3)
println(list1.getClass.getName)
不可變的list
在list1前面使用0::創(chuàng)建一個list1衣陶,但是list1結(jié)果不變
一下都是在頭部追加
0::list1;res5: List[Int] = List(0, 1, 2, 3)
res8: List[Int] = List(1, 2, 3)
scala> list1.::(0)
res10: List[Int] = List(0, 1, 2, 3)
scala> 0 +:list1
res11: List[Int] = List(0, 1, 2, 3)
list1是不可變的蔬芥,但是可以基于list1進(jìn)行操作產(chǎn)生新的list
在尾部追加
scala> list1 :+ 4
res12: List[Int] = List(1, 2, 3, 4)
scala> list1 ++: list2
res13: List[Int] = List(1, 2, 3, 5, 5, 6)
//兩個list合并
創(chuàng)建可變的list
import scala.collection.mutable.ListBuffer
var list3= ListBuffer(1,3,4)
list追加元素鹦蠕,不會產(chǎn)生新的list
list3 += 4
list.append(3)
ar list4 = new ListBuffer[Int]()
list4: scala.collection.mutable.ListBuffer[Int] = ListBuffer()
scala> list4.append(8)
scala> list4.append(9)
scala> list3++list4//產(chǎn)生新的集合
res18: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 3, 4, 4, 8, 9)
//也是新建一個list而不是增加元素
scala> list4 :+9
res19: scala.collection.mutable.ListBuffer[Int] = ListBuffer(8, 9, 9)
scala> list4
res20: scala.collection.mutable.ListBuffer[Int] = ListBuffer(8, 9)
list4.map(_*10)
res22: scala.collection.mutable.ListBuffer[Int] = ListBuffer(80, 90)
scala> list4.map{println("hello");_*10}
hello
res27: scala.collection.mutable.ListBuffer[Int] = ListBuffer(80, 90)
scala> list4.map{e=>println("hello");e*10}
hello
hello
res28: scala.collection.mutable.ListBuffer[Int] = ListBuffer(80, 90)