Almost all languages provide an array of such data structures. The data structure of the array has the advantages of fast value, fast updating and fast addition. Of course there are shortcomings.
, such as insert slow, delete slow, etc. (insert Delete for arraybuffer). In this section, we'll look at the arrays in Scala.
1. Fixed-length arrays
In Scala, arrays are used to represent a constant array of lengths, and the array in Scala is variable (that is, array elements support update operations)
We create an array that can be created using the Apply method of the associated object of the array class. Because the associated object is entered directly in Scala () , it is called
The Apply method of the associated object. So we can write the following code:
Val numbers = Array (1,2,3,4)
The code above generates an array that accesses a numeric value of type int, which is 4 of the length of the array.
To get the values of the array based on the index of the array, we can use:
Val first = numbers (0)
Array subscripts start with 0. Numbers (i) this is actually called the Apply method of the array class.
Since the array in Scala is variable, how do we update the elements of the array? Take a look at the following code:
Numbers (3) = 100
The above code updates the value of the fourth element in the array to 100. Numbers (i) =num this syntax is actually called the update method of the array class.
Scala also calls the Arrayops class with implicit conversions to add a number of methods that can be indirectly invoked for the array class.
In addition to using the associated object to instantiate the array class, we can also directly instantiate an instance of the array class by instantiating an instance of the arrays class by setting the type parameter, as follows:
New Array[string] (5) players (0) = "James"players (1) = "Kobe"Players (2) = "Curry"players ( 3) = "Westbrook"Players (4) = "Bosh"
The complete code is as follows:
2. Variable-length arrays
In Java, ArrayList is a variable-length array, and when the capacity of the array is exhausted, the ArrayList will apply for additional space and copy the original array elements into the past.
The implementation class for variable-length arrays in Scala is Arraybuffer.
The classes in Scala generally have a lot of methods, and we can't enumerate them again. Interested readers should read through the Scala doc.
Directly on the code:
Packagechapter03ImportScala.collection.mutable.ArrayBufferobject TestarraybufferextendsApp {//Arraybuffer can be instantiated by the associated object of the Arraybuffer, and can be directly new to the instance of the Arraybuffer class//Instantiate An instance of Arraybuffer with the associated object of the Arraybuffer. Val players = ArrayBuffer ("James") //removing the first element of a mutable array invokes the Apply method of the Arraybuffer classprintln (Players (0)) //Add an element to the tailPlayers + = "Kobe"//add multiple elements to the tail, and the parentheses are actually mutable argumentsPlayers + = ("Curry", "Westbrook") //add an array to the tailPlayers ++= Array ("Bosh", "Duncan") //Print array elements for(Player <-players) print (player+ "") //Deleting an element from the end of an array is an efficient operation because it does not cause the movement of other elements, and the trailing delete uses the following method, which is the number of elements removed from the tailPlayers TrimEnd 1//removing or inserting elements from the middle of a mutable array is inefficient. Because it causes other elements to move. //we can use insert to insert elements anywhere in a mutable arrayPlayers.insert (2, "Parker")) //Insert also has another overridden method that accepts mutable arguments and can pass in multiple elements, as follows:Players.insert (1, "Leonard", "Ginobili") //Delete element, specify array subscriptPlayers.remove (players.length-1)//removes an element that has an overloaded method that can specify the number of elements to deletePlayers.remove (0,2) //since Arraybuffer is mutable, it runs counter to the idea of functional programming. So when you're done, it's best to turn it into an array to usePlayers.toarray}
3. Iterating the array
The traversal of arrays in Scala is not the same as in Java. The Scala traversal array is basically the same way that other functional languages traverse arrays. Look at the code:
Packagechapter03object traversing an arrayextendsApp {//define a non-variable groupVal words = Array ("A", "B", "C", "D") //If you need to use a small array of arrays when iterating through an array, we can iterate through the array as follows for(i <-0 until words.length) println (i+ ":" +words (i))//If you want two elements to jump, you can iterate like this: for(I <-0 until (words.length,2)) println (i+ ":" +words (i))//If you want to iterate through an array from the end of the array, you can iterate like this: for(I <-(0 until words.length). Reverse) println (i+ ":" +words (i))//if the array subscript is not used during traversal, you can use the in-place syntax to traverse for(Word <-words) println (word)}
Some other easy-to-use points for arrays:
PackageTestImportscala.collection.mutable.ArrayBufferobject Array TestextendsApp {val arr= Array (1,2,3,4) Val Arrbuff= ArrayBuffer (1,2,3,4) //find out by printing that the array does not implement ToStringprintln (arr)//find Arraybuffer by printing realizes ToStringprintln (Arrbuff)//returns the array's and, the objects in the array must be numeric typesprintln (arrbuff.sum)//returns the maximum value of an arrayprintln (Arrbuff.max)}
4. Generating a new array
A set of methods is defined on the Scala array. Calling these methods in array does not modify the original array, but instead generates a new array. Look at the code:
PackageChapter03object generating a new arrayextendsApp {//you can use the for derivation to generate a new arrayVal A = Array (1,2,3,4,5,6,7) Val Result= for(Elem <-a) yieldElem for(r <-result) print (r+ "") println ()//The Guard can be used for filtering in the for deduction, as follows: Find the even number in the arrayVal result2 = for(Elem <-AifElem%2==0) yield Elem for(r <-result2) print (r+ "") println ()//You can use the filter function, as followsVal result3 = A.filter ((x:int) =>x%2==0) for(r <-result3) print (r+ "")}
5. Array element Ordering
The array ordering in Scala uses the ordering trait. The sort method of the array class sorted is implicitly converted to a call to Arrayops.
In order to reduce the complexity of the problem, we use Arraybuffer as an example to explain.
In Scala, objects are sorted in general with the help of ordering traits. There is an abstract method compare the ordering trait. As follows:
So when we compare the size of the array elements, we simply pass the sorted method to the ordering implementation class. Take a look at a simple example:
Package Test Import extends App { = ArrayBuffer (8,2,4,1,9,5) = numbers.sorted // Use the Mkstring method to specify the split character, which can be printed quickly. println (sorted mkstring "" ) }
This completes the sorting of the Array[int] array. The attentive reader may have discovered that we did not give the sorted method the ordering implementation class.
。 To explain the problem, we need to look at the signature of the sorted class:
As you can see from the above method, the sorted class accepts a ordering class parameter, and the parameter is an implicit parameter. The associated objects of the ordering class also define a number of
An implicit object, as follows:
In fact, all of the classes in Scala that inherit from Anyval do not need to implement ordering[t manually], because Scala has helped you get it done.
The implementation class for example Ordering[int] is actually bigint (not bigint in the Scala.math package). As follows:
It is for this reason that we do not need to implement ordering for the classes that inherit from Anyval.
Even ordering[string] does not have to be implemented manually (ordering's companion object has already helped us)
PackageTestImportscala.collection.mutable.ArrayBufferobject simple Array sortingextendsApp {val numbers= ArrayBuffer (8,2,4,1,9,5) //ordering's associated objects have helped us to achieve the ordering[int], direct use canVal sorted =numbers.sorted//by using the Mkstring method, you specify the split character and you can print the array quickly. println (sorted mkstring "" ) //Sorting algorithms can also be specified, this time in reverse orderVal sorted2 = numbers.sorted (NewScala.math.ordering[int] () {def compare (X:int, y:int): Int=y-x}) println (Sorted2 mkstring" " ) //ordering's associated objects have helped us achieve the ordering[string], direct use can be appliedVal players = ArrayBuffer ("G", "F", "T", "a") Val sorted3=players.sorted println (sorted3 mkstring" " ) }
Here are a few examples of complex array sorting, as follows:
Packagetestobject Complex Array orderingextendsApp {//to define a complex arrayVal pairs = Array ("A", 5, 2), ("C", 3, 1), ("B", 1, 3)) //we sort by the second field and need to customize the orderingVal sorted = pairs.sorted (Newscala.math.ordering[(String,int,int)] () {def compare (x: (String,int,int), Y: (string,int,int)): Int={x._2-y._2}}) println (sorted mkstring" ") //The following shows how to first sort by the third field, using the custom orderingVal pairs2 = Array ("A", 5, 3), ("C", 3, 1), ("B", 1, 3)) //Compare method of customizing implementation orderingVal sorted2 = pairs2.sorted (Newscala.math.ordering[(String,int,int)] () {def compare (x: (String,int,int), Y: (string,int,int)): Int={ if(x._3>y._3) 1Else if(x._3<y._3)-1ElseX._1.compareto (Y._1)}}) println (Sorted2 mkstring" ") //in fact, in Scala, ordering comes with two ways to simplify the above code, as follows://we sort by the second fieldVal sorted3 = pairs.sorted (ordering.by[(String,int,int), Int] ((x: (string,int,int)) = =x._2)) //The following shows how to sort by the third field first, in accordance with the first sortVal sorted4 = pairs2.sorted (ordering[(Int, String)].on[(String,int,int)] ((x: (string,int,int)) = =(X._3, x._1))) println (sorted4 mkstring" ")}
6. Two-dimensional array
Two-dimensional arrays do not want to say, see the following example:
Packagetestobject Multidimensional ArraysextendsApp {//array is defined with the associated object of array, the length of the second dimension is not the sameVal matrix = Array[array[int]] (Array (1), array (+), array ()) for(M <-matrix;n <-m) print (n+ "");p rintln () println (Matrix (0). Length) println (Matrix (1). Length) println (Matrix (2). Length)//use Ofdim to create two-dimensional arrays with the same length of each dimensionVal matrix2 = Array.ofdim[int] (3, 3); Matrix2 (1) (1) =1println (matrix2 (0). Length) println (matrix2 (1). Length) println (matrix2 (2). Length)}
Interoperability of 7.scala arrays and Java
The arrays in Scala can be converted to each other using Scala's implicit conversion and the Java list. Directly on the code, use the time to check back
PackageTest//convert the buffer in Scala to list in JavaImportscala.collection.JavaConversions.bufferAsJavaList//convert list in Java to buffer in ScalaImportScala.collection.JavaConversions.asScalaBufferImportScala.collection.mutable.ArrayBufferImportScala.collection.mutable.Bufferobject Interoperability with JavaextendsApp {val Commond= ArrayBuffer ("ls", "-al", "/Home") //convert the buffer in Scala to list in JavaVal PB =NewProcessbuilder (Commond) Pb.start ()//convert list in Java to buffer in ScalaVal cmd:buffer[string] =Pb.command ()}
5. Arrays