Thursday 15 May 2014

scala - Initializing an array so that each element of it would be equal to its index -


I want to initialize an array so that each element is equal to its index:

  Def method1 (obj: AnyRef) = {// .... if (obj.isInstanceOf [Array [int]] {val arr1 = obj.asInstanceOf [Array [int]] val arr2: Array [Int] = New Array [int] (arr1.length) // initial2 arr2. how? Arr2 / arr2 [0] = 0, arr2 [1] = 1, etc ....}    

You can use range to array . P>

  var arr2 = arr1.indices.toArray  method  index  / code>  

if you have an array and fill it out You can use the copyToArray method:

  (up to 0 arr2.length) .copyToArray (arr2)   

There is no performance difference between this method: toArray method copyToArray . Only <3> code field: start , expiration and phase

range , then there is almost no memory overhead.

There is also category in the object:

  val arr2 = Array.range (0, Arr1.length) // contains 0, Arr1.length is not included   

There are some other methods to fill the array even before. This method is not very useful in this case.

method fill :

  var i = -1 val arr2 = array.phil (arr1 .length) ({i + = 1; I})   

method apply :

  val arr2 = Array.apply (0, (up to 1 arr1.length ): _ *) // Array (0) on empty arr1   

If you have not stored the array and you want to change your elements and You can use the collection.breakOut method to get the array :

  // It is not like that case arr arr2: Array [int] = (up to 0 arr1.length) .map (intro) (breakout)    

No comments:

Post a Comment