Scala配列——Array/ArrayBuffer

2816 ワード

1.定長配列-ARray
//   
  //   5     ,        0
  val ary1=new Array[Int](5)
  //   5      ,        null
  val ary2=new Array[String](5)

//   
  //   2   ,          ,           new   
  val ary3= Array("zhangsan","lisi")
  //
  val ary4= Array(1 to 10 :_*);

  println("     :"+ary1(0))
  //  
  ary1(0)=11
  println("        :"+ary1(0))
  • 配列の一般的な方法
  •   val numbers = Array(1, 2, 3, 4) //        
      val first = numbers(0) //        
      numbers(3) = 100 //         100
      val biggerNumbers = numbers.map(_ * 2) //      2
    
      val a = Array(1,2)
      val b = Array(3,4)
      val c = a ++ b
      //c     (1,2,3,4)
      
      val a = Array(1, 2, 3,4,4,5,6,6)
      val c = a.distinct
      println(c.mkString(","))    // 1,2,3,4,5,6
    
     mkString   
      var array=Array(1 to 10 : _ *)
      println(array.mkString)
      println(array.mkString(","))
      println(array.mkString("(",",",")"))
        :
      12345678910
      1,2,3,4,5,6,7,8,9,10
      (1,2,3,4,5,6,7,8,9,10)
    
     //       
     val a = Array(1, 2, 3, 4, 5)
     val sum = a.sum
     //        
     val max = a.max
     //       
     val min = a.min
     //        
     scala.util.Sorting.quickSort(a)
     // toString  
     a.toString
     b.toString
    

    2.ArrayBuffer-変長配列
  • 毎回フルリミットネーミングを使用したくない場合は、ArrayBufferクラスimport scala.collection.mutable.ArrayBuffer
  • を予め導入しておくことができます.
      //    ArrayBuffer
      var numArrayBuffer = new ArrayBuffer[Int]();
    
      //   +=   ,        ,      
     //            !  spark                !
      numArrayBuffer += 1
      numArrayBuffer += (2, 3, 4, 5)
        //   ++=   ,              
      numArrayBuffer ++= Array(6, 7, 8, 9, 10)
    
      //   insert()             
      //           ,                
      numArrayBuffer.insert(5, 6)
      numArrayBuffer.insert(6, 7, 8, 9, 10)
      //   remove()             
      numArrayBuffer.remove(1)
      numArrayBuffer.remove(1, 3)
      // Array ArrayBuffer        
      numArrayBuffer.toArray
      numArrayBuffer.toBuffer
      //   trimEnd()  ,              
      numArrayBuffer.trimEnd(5)
    

    3.配列遍歴
     for (i 

    4.ArrayとArraybuffer間の変換
    scala> import scala.collection.mutable.ArrayBuffer
    import scala.collection.mutable.ArrayBuffer
    
    scala> val a = ArrayBuffer[Int]()
    a: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()
    
    scala> a.to
    to         toIndexedSeq   toList       toSeq      toString
    toArray    toIterable     toMap        toSet      toTraversable
    toBuffer   toIterator     toParArray   toStream   toVector
    
    scala> a.toArray
    res31: Array[Int] = Array()
    
    scala>
    

    配列間の変換は元の配列を修正することなく、新しい配列を生成する.
    5.多次元配列
    scala> val matrix = Array.ofDim[Double](2,3)
    matrix: Array[Array[Double]] = Array(Array(0.0, 0.0, 0.0), Array(0.0, 0.0, 0.0))
    
    scala> for(i  for(i