Scala 简单集合

2017-10-02  本文已影响0人  wangdy12

集合被分为两种:可变和不可变的集合(mutable and immutable collections)
不可变集合修改后返回一个新的集合,类似Java的String

所有的集合类都是在scala.collection包中,或者它的子包mutable, immutable, 和 generic

默认情况下,Scala 选择不可变集合,例如不加前缀的Set,使用的是scala.collection.immutable.Set,该类型定义在scala自动引入的对象Predef

包中类的层次结构

scala.collection
他们都是顶层的抽象类或traits,通常都有可变和不可变的实现

scala.collection.immutable包中的集合

scala.collection.mutable包中的集合

数组

在Scala中,数组是一种特殊的collection。
与Java数组是一一对应的,但Scala数组是一种泛型Array[T],同时Scala数组与序列sequence是兼容的,在需要Seq[T]的地方可由Array[T]代替,Scala数组支持所有的序列操作。

原理:数组和scala.collection.mutable.WrappedArray这个类的实例之间可以进行隐式转换(从Scala 2.8开始),后者则是Seq的子类

数组元素的访问使用的是圆括号

当把一个或多个值通过括号放在一个对象的旁边,Scala会把代码转换为调用对象的名为apply的方法(对象必须定义了这个方法)

类似的,在赋值时,变量后带圆括号和参数,转换为updata方法,把圆括号和等号右边的对象都作为参数

array1(0) =  "hello" 等价 array1.update(0,"hello")

定义

final class Array[T](_length: Int)

def length: Int 
def apply(i: Int): T
def update(i: Int, x: T)
override def clone(): Array[T]

常用方法

import Array._
val testStrings = new Array[String](3)
val numNames = Array("zero", "one", "two")//实际调用伴生对象的apply函数

var myMatrix = ofDim[Int](3,3)//定义一个3*3的二维数组

var myList1 = Array(1.9, 2.9, 3.4, 3.5)
var myList2 = Array(8.9, 7.9, 0.4, 1.5)

var myList3 =  concat( myList1, myList2)//合并数组

var myList1 = range(10, 20, 2)//区间范围内的数组,指定步长  -->10 12 14 16 18

遍历

for(element <- myArray)
for(i <- 0 to myArray.length-1)    println(myArray(i))
for(i <- 0 until myArray.length)    println(myArray(i))

列表 List

列表是一种有限的不可变序列式。List可以说是Scala中最重要的数据结构。 Scala.Listjava.util.List是不同的,前者是不可变序列,主要被设计用来实现函数式编程

创建

使用apply方法

val fruit: List[String] = List("apples", "oranges", "pears")

::,发音“cons” ,把一个新的元素,添加到已存在链表的最前方

运算符结合性:
如果一个方法的名称以冒号结尾,那这个方法是由右侧的操作数调用的

  val twoThree = List(2, 3)
  val oneTwoThree = 1 :: twoThree 等价 twoThree .::(1)

Nil表示空链表,等价于 List()

val nums = 1 :: (2 :: (3 :: (4 :: Nil)))
val nums = 1 :: 2 :: 3 :: 4 :: Nil // :: 运算符优先级从右向左

val empty = Nil

常用函数

reverse// 列表元素翻转

def isEmpty: Boolean //判断是否为空
def head: A //取出第一个元素
def tail: List[A]//取出除第一个元素之外的剩余元素

val fruit = List.fill(3)("apples") // 重复 apples 三次

连接列表
::: 操作符 或 List.:::() 方法或者List.concat(),

val fruit1 = "apples" :: ("oranges" :: ("pears" :: Nil))
val fruit2 = "mangoes" :: ("banana" :: Nil)

var fruit = fruit1 ::: fruit2
fruit = fruit1.:::(fruit2)
fruit = List.concat(fruit1, fruit2)

集合Set

Set是不包含重复元素的集合,分为可变的和不可变的集合,默认使用immutable

var s = Set(1,3,5,7)

import scala.collection.immutable.HashSet
val hashSet = HashSet("Tomatoes", "Chilies")

集合操作
并集、交集和差集,每一种运算都存在两种书写形式:字母和符号形式
intersectuniondiff对应&|&~

+++: 添加一个或者多个元素到集合,删除类似

val site1 = Set("1“)
val site2 = Set("2")

// ++ 作为运算符使用
var site = site1 ++ site2

//  ++ 作为方法使用
site = site1.++(site2)

映射Map

val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF")

->方法,实际返回一个Tuple2

方法 描述
keys 返回 Map 所有的键(key)
values 返回 Map 所有的值(value)
isEmpty 在 Map 为空时返回true

添加: +++
删除:---
查看是否存在:contains

上一篇 下一篇

猜你喜欢

热点阅读