scala:Guides and Overviews阅读笔记之一 -- Mutable and Immutable Collections

来源:互联网 发布:卡尔曼滤波器 知乎 编辑:程序博客网 时间:2024/06/07 10:17

http://docs.scala-lang.org/overviews/collections/overview.html

个人学习笔记,本人初学编程语言,力争第一遍能了解scala基本库中的API的作用并发现不理解的问题,争取再深入学习时能够有针对性的进行研究和学习。水平有限难免会有理解错误。如有读者发现错误或者有问题可以留言指教。希望大家不吝赐教!文中会引用他人的博客的连接,如遇版权问题请联系我,立刻纠正。感谢前辈们的宝贵总结。

Scala collections systematically distinguish between mutable and immutable collections. A mutablecollection can be updated or extended in place. This means you can change, add, or remove elements of a collection as a side effect. Immutable collections, by contrast, never change. You have still operations that simulate additions, removals, or updates, but those operations will in each case return a new collection and leave the old collection unchanged.

scala中有两种集合:可变的和不可变的。这里的可变是指集合的reference可以改变,不可变亦是如此。可以认为就是这个变量所拥有的指针的值不可变。但是集合中的元素是可变的,如下图:


当一个集合(这里以数组为例)初始化后,它所指向的内存空间就固定了(假设是固定长度的数组)。也就是说这个数组在内存中的位置不可变了。但是数组中每个元素的值是可以改变的,如a(0)=4后,数组的第一个元素的值就变成了4。我们再看一下改变a的值会发生什么:

scala> val a = Array(1,2,3)a: Array[Int] = Array(1, 2, 3)scala> a = Array(1,2,3,4)<console>:12: error: reassignment to val       a = Array(1,2,3,4)         ^
可以看见,当试图给a重新划分内存时候(也就是为a重新内存的地址的时候,报错了,val类型的变量不能再赋值)。

scala> var b = Array(1,2,3)b: Array[Int] = Array(1, 2, 3)scala> b = Array(1,2,3,4)b: Array[Int] = [I@6c302a1dscala> bres0: Array[Int] = Array(1, 2, 3, 4)
可以看见var申明的变量可以重新赋值。val 和 var 可以对应 immutable 和 mutable 理解。


All collection classes are found in the package scala.collection or one of its sub-packagesmutableimmutable, and generic.

scala中所有的集合类都在scala.collection这个包下面(mutable,immutable和generic)。


By default, Scala always picks immutable collections. For instance, if you just write Set without any prefix or without having imported Set from somewhere, you get an immutable set, and if you writeIterable you get an immutable iterable collection, because these are the default bindings imported from the scala package. To get the mutable default versions, you need to write explicitlycollection.mutable.Set, or collection.mutable.Iterable.

A useful convention if you want to use both mutable and immutable versions of collections is to import just the package collection.mutable.

  1. import scala.collection.mutable

Then a word like Set without a prefix still refers to an immutable collection, whereas mutable.Setrefers to the mutable counterpart.

默认情况下,scala优先使用immutable集合,如果想使用可变的集合,请明确导入collection.mutable.Setcollection.mutable.Iterable来使用可变Set和Iterable集合。



scala.collection package


scala.collection.immutable package


scala.collection.mutable package


0 0