Scala collection

collection分为以下几种类型。

  • strick 和 lazy
    lazy类型的collection只有在使用时才占用内存。
  • mutable 和 immutable

List

// List of Strings
val fruit: List[String] = List("apples", "oranges", "pears")
// List of Integers
val nums: List[Int] = List(1, 2, 3, 4)
// Empty List.
val empty: List[Nothing] = List()
// Two dimensional list
val dim: List[List[Int]] =
   List(
      List(1, 0, 0),
      List(0, 1, 0),
      List(0, 0, 1)
   )

scala还能实现一种链表list,利用符号::

// List of Strings
val fruit = "apples" :: ("oranges" :: ("pears" :: Nil))
// List of Integers
val nums = 1 :: (2 :: (3 :: (4 :: Nil)))
// Empty List.
val empty = Nil
// Two dimensional list
val dim = (1 :: (0 :: (0 :: Nil))) ::
          (0 :: (1 :: (0 :: Nil))) ::
          (0 :: (0 :: (1 :: Nil))) :: Nil

List的几个常用方法:

  • 添加一个元素在末尾
    def +[B >: A](x : B) : List[B]
List(1, 2).+(3) = List(1, 2, 3)
  • 合并两个List
val fruit1 = "apples" :: ("oranges" :: ("pears" :: Nil))
val fruit2 = "mangoes" :: ("banana" :: Nil)
var fruit = fruit1 ::: fruit2
println( "fruit1 ::: fruit2 : " + fruit )
output:fruit1 ::: fruit2 : List(apples, oranges, pears, mangoes, banana)

你可能感兴趣的:(Scala collection)