Scala学习笔记08【Scala数组实用操作】

Scala 数组实用操作实战

import scala.collextion.mutable.ArrayBuffer

object ArrayTest{

  def main(args: Array[String]): Unit = {


//-----------------------1、Scala数组基本操作-------------------------

        val nums1 = new Array[Int](10) //10 个Int元素

        val nums2 = new Array[String](10) //10 个String元素

        val nums3 = Array("Hello", "World", "!") //设置初值 nums3: Array[String] = Array(Hello, World)
        nums3(0) = "Goodbye"//第一个元素改为"Goodbye"
        for(elem <- nums3) print(elem + " ") //=> Goodbye World !

        //对数组内容进行追加、删除、插入
        val b = ArrayBuffer[Int]()
        b += 1                  //b:(1)
        b += (1, 2, 3, 4, 5)    //b:(1, 1, 2, 3, 5) 
        b ++= Array(8, 13, 21)  //b:(1, 1, 2, 3, 5, 8, 13, 21) 
        //注意:追加不同形式的内容的追加符号不同。

        b.trimEnd(5)        //切除掉后5个元素,b:ArrayBuffer(1, 1, 2)
        b.insert(2, 6)  //b(2)位置插入元素6,b:ArrayBuffer(1, 1, 6, 2)
        b.insert(2, 7, 8, 9)    //b(2)位置插入元素6,b:ArrayBuffer(1, 1, 7, 8, 9, 6, 2)

        b.remove(2)             //移除b(2)位置元素,b:ArrayBuffer(1, 1, 8, 9, 6, 2)
        b.remove(2, 3)          //移除b(2)位置后的3个元素,b:ArrayBuffer(1, 1, 2)

        b.toArray               //转换为Array类型 b:Array(1,1,2)






//-----------------------2、Scala数组进阶操作--------------------------

        //数组遍历
        for(i <- 0 until nums3.length)  println(i + ":" +nums3(i))
        /*结果: 0:Hello 1:World 2:! */

        //yield使用
        val c = Array(2, 3, 5, 7, 11)
        val result = for(elem <- c) yield 2*elem  //每个元素*2 yield返回值
        //result: Array[Int] = Array(4, 6, 10, 14, 22)


        {
            for(elem <- c if elem % 2 == 0) yield 2*elem //添加条件,只对偶数*2
            //res2: Array[Int] = Array(4)

            //上面例子的另一种写法(Scala中更专业的写法)
            c.filter(_% 2 == 0).map(2 * _) //只对偶数*2
            //res3: Array[Int] = Array(4)
        }

        //数组元素求和
        Array(1, 3, 5, 7).sum // res4: Int = 16

        //最长串
        ArrayBuffer("aaaaa", "aaaa", "aaaaaaa", "aaaaaaaaa", "aa").max //返回最长的串为"aaaaaaaaa"

        //排序
        val d = ArrayBuffer(1, 5, 3, 8, 6)
        val dSorted = d.sorted //排序:ArrayBuffer(1, 3, 5, 6, 8)

        //数组快速排序
        val e = Array(1, 5, 3, 8, 6)
        scala.util.Sorting.quickSort(e) //Array(1, 3, 5, 6, 8)

        //返回指定形式字符串
        e.mkString(" and ")        //res9: String = 1 and 3 and 5 and 6 and 8
        e.mkString("<", ", ", ">") //res10: String = <1, 3, 5, 6, 8>

        //定义矩阵
        val matrix = Array.ofDim[Double](3, 4)
        matrix(2)(1) = 42  
        matrix  
        //res13: Array[Array[Double]] = Array(Array(0.0, 0.0, 0.0, 0.0), Array(0.0, 0.0, 0.0, 0.0), Array(0.0, 42.0, 0.0, 0.0))


        val triangle = new Array[Array[Int]](3)
            for(i <- 0 until triangle.length)
                triangle(i) = new Array[Int](i + 1)
        triangle    
        //res14: Array[Array[Int]] = Array(Array(0), Array(0, 0), Array(0, 0, 0)) 

  }
}

你可能感兴趣的:(scala,array,数组,ArrayBuffe)