Scala 学习(三) 集合之数组

一,简介

二,定义数组

  2.1 定义普通数组

  2.2 定义可变数组

三,数组常用方法

  3.1 数组通用方法

  3.2 可变数组常用方法

正文

一,简介

  数组中某个指定的元素是通过索引来访问的。数组一旦定义完毕,可以改变其内部的元素,单不可以改变数组的长度。

二,定义数组

  2.1 定义普通数组

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

        // 定义长度为5,类型为整数的数组
        var arr = new Array[Int](5)

        // 定义长度为5,类型为任意的数组
        var arr1 = new Array[Any](5)
        
        // 直接定义数组里面的内容
        var arr2 = Array(1, 2, 3, 4, 5)

    }
}

  2.2 定义可变数组

import scala.collection.mutable.ArrayBuffer

object ArrayDemo2 {
    def main(args: Array[String]): Unit = {
        
        var ab = ArrayBuffer[Int]()
        
    }
}

三,数组的一些方法

  3.1 数组通用方法

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

        var arr2 = Array(1, 2, 3, 4, 3)

        // map方法/是将 array 数组中的每个元素进行某种映射操作, (x: Int) => x * 2 为一个匿名函数, x 就是 array 中的每个元素
        // 例如
        var tmp = arr2.map(x => x*2)
        print(tmp.toBuffer)  // ArrayBuffer(2, 4, 6, 8, 6)

        
        val words = Array("hello tom hello jim hello jerry", "hello Hatano")
        var tmp2 = words.map(x => x.split(" "))
        print(tmp2(0).toBuffer, tmp2(1).toBuffer) // (ArrayBuffer(hello, tom, hello, jim, hello, jerry),ArrayBuffer(hello, Hatano))

        // 扁平化操作,数组内的数组合并
        var tmp3 = tmp2.flatten
        print(tmp3.toBuffer) // ArrayBuffer(hello, tom, hello, jim, hello, jerry, hello, Hatano)


        // flatMap方法是 map再flatten
        var arr3 = Array("hello tom hello jim hello jerry", "hello Hatano")
        arr3.flatMap(x => x.split(" "))
        print(arr3.toBuffer) // ArrayBuffer(hello tom hello jim hello jerry, hello Hatano)
        

    }
}

  3.2 可变数组方法

import scala.collection.mutable.ArrayBuffer

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

        var ab = ArrayBuffer[Int]()

        // 数组添加元素
        ab.append(1)
        ab.append(2)
        ab.append(1)

        // 末尾追加单个或多个
        ab += 4
        ab += (5,5,3,2)

        // 追加一个数组
        ab ++ Array(3, 4)
        
        // 在某个位置插入元素(索引,值)
        ab.insert(2, 3)


        // 数组删除元素(索引位置)
        ab.remove(1)

        // 数组修改元素(索引, 新值)
        ab.update(0, 3)

        // 获取可变数组元素
        print(ab.toBuffer)

    }

}
原文地址:https://www.cnblogs.com/tashanzhishi/p/10954887.html