美文网首页
Scala collection

Scala collection

作者: crazydane | 来源:发表于2017-05-04 17:20 被阅读0次

    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

          本文链接:https://www.haomeiwen.com/subject/wikdtxtx.html