Scala 中序列和列表的区别

Scala 中序列和列表的区别

Scala 是 2003 年发明的一种基于编译器的编程语言。Scala 支持函数式编程和面向对象的编程。

Scala 中包含一个或多个元素的容器数据结构称为集合。本文将解释 Scala 的集合、序列列表之间的区别。

在 Scala 中使用 SequenceList

SequenceList 实现的特征,是一种集合类型,其中元素以索引方式存储。Sequence 保证不可变。

List 是一个像链表数据结构一样工作的集合。Lists 是不可变的,但是如果我们想要一个不断变化的列表,可以使用 ListBuffer,它是可变的。

Scala 的 sequence 等价于 Java 的 List,而 Scala 的 list 等价于 Java 的 LinkedList

语法:

Sequence : var mySeq = Seq(elements)

list : var myList = List(elements)

两个集合都可以存储信息,但序列列表之上有一些额外的亮点。在 Scala 中,列表是一个特定的集合,在函数式编程中被简化并经常使用。

列出示例代码:

object MyClass {
    def main(args: Array[String]) {

        val myList : List[Int] = List(11,22,33,44,55,66,77,88,99)

        println("The list is "+ myList)
    }
}

输出:

The list is List(11, 22, 33, 44, 55, 66, 77, 88, 99)

序列示例代码:

object MyClass {
    def main(args: Array[String]) {

        val mySequence : Seq[Int] = Seq(101,2020,303,404,505,606,770,808,909)

        println("The Sequence is "+ mySequence)
    }
}

输出:

The Sequence is List(101, 2020, 303, 404, 505, 606, 770, 808, 909)

根据上面的输出,我们可以观察到,在 Scala 中,默认情况下,sequence 被初始化为 list

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Suraj P
Suraj P avatar Suraj P avatar

A technophile and a Big Data developer by passion. Loves developing advance C++ and Java applications in free time works as SME at Chegg where I help students with there doubts and assignments in the field of Computer Science.

LinkedIn GitHub

相关文章 - Scala List