从零开始学Scala系列(四)之数组集合1

来源:互联网 发布:建筑测量学知乎 编辑:程序博客网 时间:2024/05/22 15:13

该小节主要是简单介绍在scala中使用数组和集合

1 数组

  • 数组声明和初始化

还是以前一样,先来个简单地例子:
这里写图片描述
初看是不是和java类型的语言类似, 当然还有更简单的用法。
注: 0 to 2 是scala中RichInt提供的方法

  /** like `until`, but includes the last index */  /**    * @param end The final bound of the range to make.    * @return A [[scala.collection.immutable.Range]] from `'''this'''` up to    *         and including `end`.    */  def to(end: Int): Range.Inclusive = Range.inclusive(self, end)

还有until… 但不包含end,比如 0 until 2 就是 0,1 当然还可以指定步长step, 想更多深入了解的可以看RichInt.scala原码。

for (i <- 0.to(2)) {      print(array(i) + " ")    }

scala中都是使用函数表示 + - * / 也不例外。用空格表示 0 to 2 只是更加简易而已,而这也是scala所追求的的,尽量做到代码简易可读性高。

好了 , 来看看数组声明初始化简易的做法:
这里写图片描述
是不是简单太多了 , 其实这是隐式调用了Array.scala中apply方法而已

/** Creates an array with given elements.   *   *  @param xs the elements to put in the array   *  @return an array containing all elements from xs.   */  // Subject to a compiler optimization in Cleanup.  // Array(e0, ..., en) is translated to { val a = new Array(3); a(i) = ei; a }  def apply[T: ClassTag](xs: T*): Array[T] = {    val array = new Array[T](xs.length)    var i = 0    for (x <- xs.iterator) { array(i) = x; i += 1 }    array  }

有兴趣的可以去看看原码。

2 List的使用

scala 中的list是immutable(不可变的),不像是java中list元素是可重新赋值的,也就是可变的。

val list = List(1, 2, 3)

这里也是隐式调用了List.scala中apply方法

override def apply[A](xs: A*): List[A] = xs.toList

scala 中的List有很多有用的方法, 这里只是简单介绍几个:

  • :::
  • ::

::: 是两个List之间拼接的方法,而且是右操作符(注:在scala中一般以冒号结尾的方法都是右操作符,比如上面这两个), 看例子:

val list1 = List(1, 2, 3)val list2 = List(4, 5)println(list1 ::: list2)输出结果:List(1, 2, 3, 4, 5)

右操作符意味着操作符由右操作数起调用方法的作用,还是上面那段代码,下面另一种写法:

val list1 = List(1, 2, 3)val list2 = List(4, 5)println(list2.:::(list1)) //这和c java中的方法调用差不多 但在scala中还是推荐第一种写法,简洁,可读性强。输出结果:List(1, 2, 3, 4, 5)

:: 方法是向List前面追加元素, 例子如下

val list1 = List(1, 2, 3)val list2 = 4 :: list1val list3 = 6 :: 5:: 4 :: list1println(list2)println(list3)输出结果:List(4, 1, 2, 3)List(6, 5, 4, 1, 2, 3)

通常 使用List时候 刚开始并不知道向其中添加什么元素,这是就需要定义一个空List,再来添加元素,在List.scala中有Nil对象就是空List:

@SerialVersionUID(0 - 8256821097970055419L)case object Nil extends List[Nothing] {  override def isEmpty = true  override def head: Nothing =    throw new NoSuchElementException("head of empty list")  override def tail: List[Nothing] =    throw new UnsupportedOperationException("tail of empty list")  // Removal of equals method here might lead to an infinite recursion similar to IntMap.equals.  override def equals(that: Any) = that match {    case that1: scala.collection.GenSeq[_] => that1.isEmpty    case _ => false  }}

下面有个简单的例子:

val list = 1 :: 2 :: 3 :: Nilprintln(list)输出结果List(1, 2, 3)

声明初始化一个List后, 我们就需要使用它, 比如获取某个下标的元素在java中使用list.get(0) 这种方式,而在scala中可以更加精简list(0), 当然List中对于取头一个元素还有一个独立的方法head:

val list = 1 :: 2 :: 3 :: Nilprintln(list(0))println(list.head)println(list head) // 在scala方法调用可以用空格代替. 两种方式随意使用哪种输出结果111

tail 方法
List中也有tail方法, 但是它和head方法不一样,并不是返回List中的最后一个元素, 而是返回除去第一个元素包含剩余元素的新List(当原List只有一个元素时,返回空List):

val list = 1 :: 2 :: 3 :: Nilprintln(list tail)val list2 = 1 :: Nilprintln(list2 tail)输出结果List(2, 3)List()

当然scala中List还有很多其他有用方法,就不一一赘述了。

2 Tuple(元组)的使用

tuple在scala中也是immutable(不可变的), 但它不像List, 它可以包含不同类型的元素,有几个元素就称为几元组

//一元组val tuple1 = Tuple1(1)println(tuple1._1)//二元组第一种定义方式val tuple2 = Tuple2("0", 1)println(tuple2._1, tuple2._2)//二元组第一种定义方式val tuple2_2 = ("0", 1)println(tuple2_2._1, tuple2_2._2)输出结果1(0,1)(0,1)

可以看看scala中的元组原码:

/** A tuple of 2 elements; the canonical representation of a [[scala.Product2]]. * *  @constructor  Create a new tuple with 2 elements. Note that it is more idiomatic to create a Tuple2 via `(t1, t2)` *  @param  _1   Element 1 of this Tuple2 *  @param  _2   Element 2 of this Tuple2 */final case class Tuple2[@specialized(Int, Long, Double, Char, Boolean/*, AnyRef*/) +T1, @specialized(Int, Long, Double, Char, Boolean/*, AnyRef*/) +T2](_1: T1, _2: T2)  extends Product2[T1, T2]{  override def toString() = "(" + _1 + "," + _2 + ")"  /** Swaps the elements of this `Tuple`.   * @return a new Tuple where the first element is the second element of this Tuple and the   * second element is the first element of this Tuple.   */  def swap: Tuple2[T2,T1] = Tuple2(_2, _1)}

目前scala中一共有22元组,当然如果 需要更多 也可以进行模仿自定义。
这里写图片描述

这节就先到这了,下小节Set和Map,其实有了这节的概念 就很简单了,无外乎多练,多敲代码。

0 0
原创粉丝点击