基础内容
1. 数组定义
定长、可变数组的定义;元素添加,删除,排序,求和等常用运算
import scala.collection.mutable.ArrayBuffer import scala.math.BigDecimal.RoundingMode /** * @author xwolf * @date 2017-04-09 18:23 * @since 1.8 */ object Collection { def main(arg:Array[String]): Unit ={ multipleArray() } /** * 数组创建 */ private def create() :Unit={ val a = new Array[String](1) a(0)="Hello" println(a.toBuffer) val ab =ArrayBuffer(3) ab+=1 //append 可接受多个参数,在数组末尾追加元素 ab.append(12,3,3) ab ++=Array(5,12) println("insert after 1: "+ ab) ab += (3,5) println("insert after 2: "+ ab) // 在指定索引 添加元素 ab.insert(2,123,32) println("remove before:"+ab) //移除当前索引的元素 ab.remove(1) println("remove after 1:"+ ab) //移除当前索引开始的元素的个数,超出会抛出下标越界异常 ab.remove(4,3) println(ab) val ary = ab.toArray val arrayB = ary.toBuffer println(arrayB) } /** * 排序 */ def sort(){ val ary =ArrayBuffer[Int]() ary ++=Array(1,123,3,123,4,12,10) println(ary) val a = ary.sortBy(x=>x) println(a) //自定义排序 val c= ary.sortWith((a,b)=>a.compareTo(b)<0) println(c) val d= ary.sortWith((a,b)=>a.compareTo(b)>0) val f = ary.sorted println(f) println(d) //去重 过滤 map val e = d.distinct.filter(_.%(2)!=0).map(_.+(2)) println(e) } /** * 常用运算 */ def calculator():Unit={ val ary =Array(12,2,12,33,2,123,1) println(ary.max)//最大 println(ary.min)//最小值 println(ary.sum)//求和 println(average(ary))//求平均值 } /** * 求数组的平均值 四舍五入保留两位小数 * @param ary * @return */ private def average(ary:Array[Int]):BigDecimal={ val len = ary.length val sum = ary.sum (BigDecimal.valueOf(sum)./(BigDecimal.valueOf(len))).setScale(2,RoundingMode.UP) } /** * 多维数组 */ def multipleArray(): Unit ={ //多维数组定义 val mary = new Array[Array[Int]](2) mary(0)=Array(1,2,3,1,4) mary(1)=Array(2,1,4) for(ary<-mary){ println(ary.toBuffer) } //定义 2行 3列 数组 val nary =Array.ofDim[Int](2,3) nary(0)(0)=12 nary(0)(1)=13 nary(0)(2)=14 nary(1)(0)=22 nary(1)(1)=23 nary(1)(2)=24 println(nary.toBuffer) for(i<-0 until nary.length){ println(nary(i).toBuffer) } } }
scala 数组操作中使用了隐式转化.
更多资料参考:
时间: 2024-11-07 16:56:46