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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Scala的集合类可以从三个维度进行切分: 可变与不可变集合(Immutable and mutable coll...
    时待吾阅读 11,102评论 0 4
  • PARAMETERIZE ARRAYS WITH TYPES In Scala, you can instanti...
    RxCode阅读 4,296评论 0 0
  • 数组 :new Array[Int](8)与Array[Int](8)的区别:第一种8个元素,第二个定义一个值为8...
    夙夜M阅读 5,775评论 1 2
  • scala学习笔记 第2章 变量和数据类型 基本数据 scala的核心数据为四种 :字面量、值、变量、类型 值使...
    485b1aca799e阅读 6,485评论 0 1
  • 2017.8.25今天犹豫我妈不舒服又回家了一趟,一进门,这小家伙比我都积极,问长问短的,姥姥怎么了?姥姥那里疼?...
    瑜珊妈妈阅读 1,486评论 0 0

友情链接更多精彩内容