多维数组:数组的元素,还是数组,数组套数组,就是多维数组
- 构造指定行与列的二维数组:Array.ofDim方法
val multiDimArr1 = Array.ofDim[Double](3, 4)
multiDimArr1(0)(0) = 1.0
构建一个指定行与列的二维数组, eg.
package com.sunny.spark.scala.array
/**
* <Description> <br>
*
* @author Sunny<br>
* @taskId: <br>
* @version 1.0<br>
* @createDate 2018/07/14 15:10 <br>
* @see com.yrz.spark.scala.array <br>
*/
object ManyArray1 {
def main(args: Array[String]): Unit = {
//创建一个长度为3的外层数组,数组内的元素是长度为4的数组。也就是三行四列
val manyArray = Array.ofDim[Int](3,4)
manyArray(0)=Array(1,2,3,4)
manyArray(1)=Array(1,2,3,4)
manyArray(2)=Array(1,2,3,4)
/**
* 打印结果为:
* 1234
* 1234
* 1234
*/
for (elem <- manyArray) {
for (elem <- elem) {
print(elem)
}
println()
}
}
}
- 构造不规则多维数组:
val multiDimArr2 = new Array[Array[Int]](3)
multiDimArr2(0) = new Array[Int] (1)
multiDimArr2(1) = new Array[Int] (2)
multiDimArr2(2) = new Array[Int] (3)
multiDimArr2(1)(1) = 1
创建一个不规则的二维数组, eg.
package com.sunny.spark.scala.array
/**
* <Description> <br>
*
* @author Sunny<br>
* @taskId: <br>
* @version 1.0<br>
* @createDate 2018/07/14 15:13 <br>
* @see com.sunny.spark.scala.array <br>
*/
object ManyArray2 {
def main(args: Array[String]): Unit = {
//创建一个长度为3的外层数组,数组里边的元素是数组
val manyArray = new Array[Array[Int]](3)
manyArray(0) = new Array[Int](1) //第一个元素为长度为1的数组
manyArray(1) = new Array[Int](2) //第二个元素为长度为2的数组
manyArray(2) = new Array[Int](3) //第三个元素为长度为3的数组
manyArray(0)=Array(1)
manyArray(1)=Array(1,2)
manyArray(2)=Array(1,2,3)
/**
* 打印结果为:
* 1
* 12
* 123
*/
for (elem <- manyArray) {
for (elem <- elem) {
print(elem)
}
println()
}
}
}
- Java数据与Scala数组的隐式转换
Java数组隐式转换成Scala数组,在需要转换的函数前边加上隐式转换
import scala.collection.JavaConversions.asScalaBuffer
Scala数组转换成Java数组,在需要转换的函数前边加上隐式转换
import scala.collection.JavaConversions.bufferAsJavaList
Scala代码中,直接调用JDK(Java)的API,比如调用一个Java类的方法,势必可能会传入Java类型的list;Scala中构造出来的list,其实是ArrayBuffer;你直接把Scala的ArrayBuffer传入Java接收ArrayList的方法,肯定不行。
import scala.collection.JavaConversions.bufferAsJavaList
import scala.collection.mutable.ArrayBuffer
val command = ArrayBuffer("javac", "C:\\Users\\Administrator\\Desktop\\HelloWorld.java")
val processBuilder = new ProcessBuilder(command)
val process = processBuilder.start()
val res = process.waitFor()
import scala.collection.JavaConversions.asScalaBuffer
import scala.collection.mutable.Buffer
val cmd: Buffer[String] = processBuilder.command()