Scala中数组和列表的区别 [英] Difference between Array and List in scala

查看:808
本文介绍了Scala中数组和列表的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在什么情况下,我应该使用数组(缓冲区)和List(缓冲)。只有一个区别,我知道的是,数组是nonvariant和列表是协变的。但是,我们的表现和其他一些特点?

In what cases I should use Array(Buffer) and List(Buffer). Only one difference that I know is that arrays are nonvariant and lists are covariant. But what about performance and some other characteristics?

推荐答案

斯卡拉列表是不可变的递归数据结构,它是Scala这样的基本结构,你应该(可能)使用它比<$ C多$ C>阵列(实际上是的可变 - 的阵列不可改变模拟 IndexedSeq )。

Immutable Structures

The Scala List is an immutable recursive data structure which is such a fundamental structure in Scala, that you should (probably) be using it much more than an Array (which is actually mutable - the immutable analog of Array is IndexedSeq).

如果您是从Java背景的,那么显而易见的水货时使用的LinkedList 的ArrayList 。前者通常用于列出它们只会遍历的(并且其尺寸是不知道的前期),而后者应该用于列出其中或者具有已知尺寸(或最大尺寸)或这的快速随机访问的是非常重要的。

If you are coming from a Java background, then the obvious parallel is when to use LinkedList over ArrayList. The former is generally used for lists which are only ever traversed (and whose size is not known upfront) whereas the latter should be used for lists which either have a known size (or maximum size) or for which fast random access is important.

ListBuffer 提供一个固定时间转换为列表这是理由单独使用 ListBuffer 如果需要这样以后转换。

ListBuffer provides a constant-time conversion to a List which is reason alone to use ListBuffer if such later conversion is required.

Scala的阵列应在JVM通过Java数组来实现的,因此一个数组[INT] 可能是更高性能(作为 INT [] )比列表[INT] (将箱中的内容,除非你正在使用的有新的 @specialized 功能斯卡拉的最新版本)。

A scala Array should be implemented on the JVM by a Java array, and hence an Array[Int] may be much more performant (as an int[]) than a List[Int] (which will box its contents, unless you are using the very latest versions of Scala which have the new @specialized feature).

不过,我认为使用阵列 S IN斯卡拉应保持在最低限度,因为这感觉就像是你真的需要知道什么是引擎盖下回事决定是否你真的阵列将所需的基本类型进行备份,也可以作为装箱的包装类型。

However, I think that the use of Arrays in Scala should be kept to a minimum because it feels like you really need to know what is going on under the hood to decide whether your array really will be backed by the required primitive type, or may be boxed as a wrapper type.

这篇关于Scala中数组和列表的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆