欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

scala定长数组和可变数组

程序员文章站 2022-03-04 14:01:51
...

定长数组

  def main(args: Array[String]): Unit = {
    //使用new创建定长8的数组,默认值和类型相关
    val arr1 = new Array[Int](5)
    println(arr1) //打印地址
    println(arr1.toBuffer)  //将数组的值放到buffer

    //不使用new方式来定义变长数组,Array定义,实则用Array的apply()方法
    val arr2 =Array[Int](8)
    println(arr2.toBuffer)  //赋值元素为8

    //定义数组并赋值
    val arr3 = Array(123,"hello",'a',789)
    println(arr3.toBuffer)  //ArrayBuffer(123, hello, a, 789)

    //操作可变数组
    var arr4 = new Array[String](4)
    //赋值
    arr4(0) = "hello"
    arr4(1) = "hadoop"
    arr4(2) = "hive"
    arr4(3) = "spark"
    //打印
    println(arr4.toBuffer)  //ArrayBuffer(hello, hadoop, hive, spark)

    //修改值
    arr4(1) = "scala"
    println(arr4.toBuffer)  //ArrayBuffer(hello, hadoop, hive, spark)
    arr4.update(0,"hbase")

    //获取元素
    println(arr4(1))
    println(arr4.apply(1))

    //遍历
    for(i <- arr4){
      print(i + " ")
    }

    println()

    //如果数组想删除,需要转换成list
    val list = arr4.toList
    println(list)
    val li = list.drop(1)
    println(li) //List(scala, hive, spark)
    //tail是取集合从后往前的除第一个以外的元素
    println(li.tail)  //List(hive, spark)
  }

可变数组

object MutableArray {
  def main(args: Array[String]): Unit = {
  //使用new ArrayBuffer()  定义一个可变的数组
    val arr1 : ArrayBuffer[String] = new ArrayBuffer[String]()
    
    //添加元素
    arr1 += "hadoop"
    //arr1(1) = "spark"
    arr1 += ("hive","hbase")
    arr1 ++= ArrayBuffer("scala","sqoop")
    println(arr1)

    //在指定位置添加元素
    arr1.insert(1,"flume")
    arr1.insert(1,"kafka","kylin")
    arr1.insertAll(1,ArrayBuffer("hello","world"))
    println(arr1)

    //更新元素
    arr1(1) = "insistent"
    arr1.update(2,"java")

    println(arr1)

    //获取指定元素
    println(arr1(1))
    println(arr1.apply(2))
    println(arr1.take(3))

    //遍历
    for(i <- arr1){
      print(i + " ")
    }
    println()

    //删除元素
    arr1 -= "insistent"
    arr1 -= ("java","kafka")
    arr1.remove(1)
    arr1.remove(1,3)
    arr1.trimEnd(1) //从后往前移除n个元素
    arr1.trimStart(1) //从后往前移除n个元素
    println(arr1)

  }
相关标签: scala