Scala 数组array操作
package scala_learn.demo11_Collection
import scala.collection.mutable.ArrayBuffer
object O1_Array {
def main(args: Array[String]) {
test5()
}
def test11(): Unit = {
val arr = ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
println(arr.sum)
println(arr.min)
println(arr.max)
println(arr.count(_ % 2 == 0))
val arr2 = arr.sorted
println(arr)
println(arr2)
println(arr.sortWith(_ < _))
println(arr.sortWith(_ > _))
println(arr.mkString("-"))
println(arr.mkString("<<", "-", ">>"))
}
def test10(): Unit = {
val b = new ArrayBuffer[Int]()
println(b)
b += 2
println(b)
b +=(3, 4, 5, 6, 7, 8)
println(b)
b ++= Array(3, 4, 2)
println(b)
b.trimEnd(2)
println(b)
b.trimStart(2)
println(b)
b.insert(2, 0)
println(b)
b.insert(2, 1, 4, 7)
println(b)
b.remove(2, 3)
println(b)
b.remove(2)
println(b)
val arr = b.toArray
println(arr.getClass)
val c = arr.toBuffer
println(c)
}
def test9(): Unit = {
import scala.Array._
val myMatrix = ofDim[Int](3, 3)
for (i <- 0 to 2) {
for (j <- 0 to 2) {
myMatrix(i)(j) = j * i
}
}
for (i <- 0 to 2) {
for (j <- 0 to 2) {
print(" " + myMatrix(i)(j))
}
println()
}
}
def test8(): Unit = {
val arr = new Array[Int](12)
arr match {
case a: Array[Int] => println("right")
case _ => println("error")
}
}
def test5(): Unit ={
val arr = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
val arr2=arr.map(_*2)
for (e<-arr2){
print(e)
}
println()
val arr3=arr.filter(x=>(x%2)!=0)
for (e<-arr3){
print(e)
}
println()
val max=arr.max
println("max="+max)
val min=arr.min
println("min="+min)
val arr4=arr.sorted
for (e<-arr4){
print(e)
}
println()
scala.util.Sorting.quickSort(arr)
for (e<-arr){
print(e)
}
println()
val s = Array("zhangsan","lisi","wangwu")
val a = Array(18,20,19)
val sa = s.zip(a)
for (e<-sa){
print(e)
}
println()
}
def test4(): Unit = {
val arr = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
for (i <- 0 until arr.length) {
print(arr(i) + "\t")
}
println()
for (i <- 0 until arr.length reverse) {
print(arr(i) + "\t")
}
println()
for (i <- 0 until(arr.length, 2)) {
print(arr(i) + "\t")
}
println()
for (e <- arr) {
print(e + "\t")
}
println()
}
def test3(): Unit ={
var myList1 = Array(1.9, 2.9, 3.4, 3.5)
for (i <- myList1) {
print(i)
}
import scala.Array._
var myList2 = range(10, 20, 2)
var myList3 = range(10, 20)
for (x <- myList1) {
print(" " + x)
}
println()
for (x <- myList2) {
print(" " + x)
}
}
def test2(): Unit = {
val arr = new Array[Int](12)
for (i <- 0 until arr.length) {
arr(i) = (i * i)
}
for (i <- 0 until arr.length) {
print(arr(i) + "\t")
}
}
def test1(): Unit = {
val arr = new Array[Int](12)
println(arr.length)
for (i <- 0 until arr.length) {
print(arr(i) + "\t")
}
}
}