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

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

问题描述

在什么情况下我应该使用 Array(Buffer) 和 List(Buffer).我所知道的唯一一个区别是数组是非变量的,而列表是协变量的.但是性能和其他一些特性呢?

解决方案

Immutable Structures

Scala List 是一个不可变的递归数据结构,它是 Scala 中的一个基本结构,您应该(可能)使用它比 Array (这实际上是可变 - Array不可变模拟IndexedSeq).

如果您有 Java 背景,那么明显的相似之处是何时使用 LinkedList 而不是 ArrayList.前者通常用于只遍历(并且其大小预先未知)的列表,而后者应该用于具有已知大小(或最大大小)或快速随机访问很重要.

可变结构

ListBuffer 提供到 List 的恒定时间转换,如果需要稍后的转换,这就是使用 ListBuffer 的唯一原因.>

Scala Array 应该由 Java 数组在 JVM 上实现,因此 Array[Int] 可能性能更高(作为 int[]) 而不是 List[Int](这将装箱其内容,除非您使用具有新 @specialized 的最新版本的 Scala功能).

然而,我认为在 Scala 中使用 Arrays 应该保持在最低限度,因为感觉你真的需要知道幕后发生的事情来决定你的数组是否真的将由所需的原始类型支持,或者可以作为包装器类型装箱.

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?

解决方案

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).

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.

Mutable Structures

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

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).

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天全站免登陆