Scala collection

2017-05-04  本文已影响0人  crazydane

collection分为以下几种类型。

List

// List of Strings
val fruit: List[String] = List("apples", "oranges", "pears")
// List of Integers
val nums: List[Int] = List(1, 2, 3, 4)
// Empty List.
val empty: List[Nothing] = List()
// Two dimensional list
val dim: List[List[Int]] =
   List(
      List(1, 0, 0),
      List(0, 1, 0),
      List(0, 0, 1)
   )

scala还能实现一种链表list,利用符号::

// List of Strings
val fruit = "apples" :: ("oranges" :: ("pears" :: Nil))
// List of Integers
val nums = 1 :: (2 :: (3 :: (4 :: Nil)))
// Empty List.
val empty = Nil
// Two dimensional list
val dim = (1 :: (0 :: (0 :: Nil))) ::
          (0 :: (1 :: (0 :: Nil))) ::
          (0 :: (0 :: (1 :: Nil))) :: Nil

List的几个常用方法:

List(1, 2).+(3) = List(1, 2, 3)
val fruit1 = "apples" :: ("oranges" :: ("pears" :: Nil))
val fruit2 = "mangoes" :: ("banana" :: Nil)
var fruit = fruit1 ::: fruit2
println( "fruit1 ::: fruit2 : " + fruit )
output:fruit1 ::: fruit2 : List(apples, oranges, pears, mangoes, banana)
上一篇下一篇

猜你喜欢

热点阅读