创建list
var list1 = List(1,2,3)
println(list1.getClass.getName)
不可变的list
在list1前面使用0::创建一个list1,但是list1结果不变
一下都是在头部追加
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进行操作产生新的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合并
创建可变的list
import scala.collection.mutable.ListBuffer
var list3= ListBuffer(1,3,4)
list追加元素,不会产生新的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//产生新的集合
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)
网友评论