Scala collections are also divided into immutable collections and mutable collections. The set includes sequence Seq, set Set, and mapping Map, which are also divided into immutable and variable.
Immutable list
Define List, including apply, :: Nil, and ::: to define List.
Nil is an empty set, :: is the head element and the tail list to form a new list, and this is calculated from the back, so the following is also calculated relative to 3::Nil first, and then 2::(3: : Nil), and finally 1::(2::(3 :: Nil)).
If the head is a List, then if you use ::, the first element is still a List, so you need to use ::: to form a new list, you can look at the following list3 and list4.
// 定义List
val list1: List[Int] = List(1, 2, 3)
val list2: List[Int] = 1 :: 2 :: 3 :: Nil
val list3: List[Any] = list1 :: list2
val list4: List[Int] = list1 ::: list2
println(list1) // List(1, 2, 3)
println(list2) // List(1, 2, 3)
println(list3) // List(List(1, 2, 3), 1, 2, 3)
println(list4) // List(1, 2, 3, 1, 2, 3)a
Read List:
// 取指定位置
println(list1(0)) // 1
// 取第一个无素
println(list1.head) // 1
// 取第一个无素后的剩余列表
println(list1.tail) // List(2, 3)
// 取第二个无素
println(list1.tail.head) // 2
// 取最后一个无素
println(list1.last) // 3
// 取最后一个无素后的剩余列表
println(list1.init) // List(1, 2)
// 倒序
println(list1.reverse) // List(3, 2, 1)
// 获取前N个元素
println(list1.take(2)) // List(1, 2)
// 字符串拼接
println(list1.mkString("-")) // 1-2-3
New elements:
// 前面加元素
val list5_1 = list1.+:(100)
println(list5_1) // List(100, 1, 2, 3)
val list5_2 = 100 +: list1
println(list5_2) // List(100, 1, 2, 3)
val list5_3 = 100 :: list1
println(list5_3) // List(100, 1, 2, 3)
val list5_4 = list1.::(100)
println(list5_4) // List(100, 1, 2, 3)
// 后面加元素
val list6_1 = list1.:+(4)
println(list6_1) // List(1, 2, 3, 4)
val list6_2 = list1 :+ 4
println(list6_2) // List(1, 2, 3, 4)
The traversal is the same as the array , which is not demonstrated here.
Variable ListBuffer
Define ListBuffer
// 定义ListBuffer
val list1: ListBuffer[Int] = ListBuffer()
val list2: ListBuffer[Int] = ListBuffer(1, 2, 3)
println(list1) // ListBuffer()
println(list2) // ListBuffer(1, 2, 3)
Read ListBuffer, ibid.
Modify the specified element:
list2(0) = 11
println(list2) // ListBuffer(11, 2, 3)
list2.update(0, 1)
println(list2) // ListBuffer(1, 2, 3)
New elements:
// 后面加元素
list2.+=(4)
println(list2) // ListBuffer(1, 2, 3, 4)
list2 += 5
println(list2) // ListBuffer(1, 2, 3, 4, 5)
list2.append(6)
println(list2) // ListBuffer(1, 2, 3, 4, 5, 6)
// 前面加元素
list2.prepend(100)
println(list2) // ListBuffer(100, 1, 2, 3, 4, 5, 6)
// 指定位置加元素
list2.insert(1, 101)
println(list2) // ListBuffer(100, 101, 1, 2, 3, 4, 5, 6)
Delete elements, similar to an array here
list2.remove(0)
println(list2) // ListBuffer(101, 1, 2, 3, 4, 5, 6)
list2.remove(1, 3)
println(list2) // ListBuffer(101, 4, 5, 6)
list2 -= 4
println(list2) // ListBuffer(101, 5, 6)
The traversal is the same as the array , which is not demonstrated here.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。