Getting Started with Scala learning note three--array usage

Source: Internet
Author: User
Tags array definition arrays numeric scala tutorial
PrefaceThis article is mainly about Scala's array, Bufferarray, List, more tutorials Please refer to: Scala tutorial This article summarizes the knowledge pointsIf the length is fixed, use array, if the length may vary, use Arraybuffer to provide the initial value, do not use new, the complex object array does not provide the initial value when you must provide new () to access the element with for (Elem <-arr) to traverse the array with for ( Elem <-arr If ...) ... yield ... To transform the original array into a new array. Scala arrays and Java arrays can interoperate Array

1, fixed-length array definition:

Defines a numeric array of length 10
scala> val numberarray = new Array[int] (Ten)
numberarray:array[int] = Array ( 0,0,0,0,0,0,0,0,0,0)
//define a String class array of length 10
scala> val strarray = new array[string] (Ten)
Strarray: Array[string] = array (null, NULL, NULL, NULL, NULL, NULL, NULL)

//As can be seen from above, the complex object type is initialized to NULL when the array is defined, and the numeric type is Initialized to 0, and the above complex type definition must be added new, otherwise it will error

//provide an array of definitions of the initial value
scala> val strArray2 = Array ("First", "Second")  // This indicates that the initial value provided does not require new
strarray2:array[string] = Array (First, Second)

scala> strArray2 (0) = "Goodbye"
Strarray2:array[string] = Array (Goodbye, Second)
2, variable length array definition for the length needs to change the array, Java has arraylist,c++ vector. The equivalent data structure in Scala is Arraybuffer
Importing variable packages, the mutable collections in Scala are placed in mutable, and imported scala> import Scala.collection.mutable.ArrayBuffer when used Scala.collection.mutable.ArrayBuffer scala> val ArrayBuffer = Arraybuffer[int] () ArrayBuffer: Scala.collection.mutable.arraybuffer[int] = ArrayBuffer ()//Add a value at the tail scala> ArrayBuffer + = 1 Res17:arrayBuffer.type

= ArrayBuffer (1)//Add multiple elements at the tail scala> ArrayBuffer + = (2, 3, 4, 5) Res19:arrayBuffer.type = ArrayBuffer (1, 2, 3, 4, 5)

Add a collection at the tail scala> arrayBuffer ++= Array (6, 7, 8, 9) Res20:arrayBuffer.type = ArrayBuffer (1, 2, 3, 4, 5, 6, 7, 8, 9)
Remove the last 2 elements scala> arraybuffer.trimend (2)//Remove 11 elements from the beginning scala> Arraybuffer.trimstart (2) scala> ArrayBuffer Res23:scala.collection.mutable.arraybuffer[int] = ArrayBuffer (2, 3, 4, 5, 6, 7)//insert or delete element scala> at any location arraybuffer.i Nsert (2, 6)//arraybuffer (2, 3, 6, 4, 5, 6, 7) scala> Arraybuffer.insert (1, 2, 3, 4)//arraybuffer (2, 1, 2, 3, 4, 3, 6 , 4, 5, 6, 7) scala> Arraybuffer.remove (2)//arraybuffer (2, 1, 3, 4, 3, 6, 4, 5, 6, 7) scala> Arraybuffer.remover (1, 8)//arraybuffer (2, 7) 
3. Variable-length array and fixed-length array conversion
Variable length conversion long fixed length
scala > Arraybuffer.toarray
//array (2, 7)

//fixed length converted to variable length
scala>res7.tobuffer
// ArrayBuffer (2, 7)
4. Traversing fixed-length and variable-length arrays
for (i <-0 until.arrayBuffer.length)
    println (i + ":" + A (i))

0 Until.arrayBuffer.length is actually a method call that returns an interval Range:0.until (arraybuffer.length) for (i

Enhanced for for
(i <-arrayBuffer)
    println (i + ":" + A (i))

5. Array conversion
In the "Getting Started with Scala" note two-basic data type, program control structure mentioned in the for-loop derivation, you can use the original array to produce a new array.

Scala> val A = Array (2, 3, 5, 7, one)
a:array[int] = Array (2, 3, 5, 7, one)
//This creates a new array, the original array is also in
Scala> ; Val result = for (Elem <-a) yield 2 * elem
Result:array[int] = Array (4, 6, 10, 14, 22)

If a fixed-length array is used for, then for (...) ... yield is a fixed-length array, and if you are using a variable-length array, you get a variable-length array Scala also provides another way

Scala> A.filter (_% 2 = = 0). Map (2 * _)

even
scala>a.filter (_% 2 = = 0). Map{2 * _}

Example:
Given an integer buffer array, we want to remove all negative numbers except for the first negative number. There are several practices

First approach:
var = true
var n = a.length
var i = 0 while
(i < n) {
    if (a (i) > 0) i + = 1
    else{
        if (first) {first = false; I + = 1}
        else {a.remove (i); n-= 1}}
}

//second approach:
// First, a new array is used to record the subscript of the array that satisfies the condition.
val
indexes = True val = for (i <-0 until a.length if first | | A (i) > 0) Yie LD {
    if (a (i) < 0) First = false; I
}
//Then move the element to that go position, truncate end for
(J <-o until Indexes.length) a (j) = A (Indexes (j))
A.trimend (a.length-indexes.length)

6. Common algorithms
Scala provides a common function for arrays

//defines an integer array scala> val intarr=array (1,2,3,4,5,6,7,8,9,10) Intarr:array[int] = Array (1, 2, 3  , 4, 5, 6, 7, 8, 9, 10)//sum scala> intarr.sum res87:int = 55//MAX scala> Intarr.max res88:int = scala> ArrayBuffer ("Hello", "Hell", "Hey", "Happy"). Max res90:string = Hey//Find minimum scala> intarr.min res89:int = 1//Sort//sor The Ted method sorts the array or array buffers and returns a sorted array or array buffer, the original array is retained Scala>val B = ArrayBuffer (1, 7, 2, 9) B:arraybuffer[int] = ArrayBuffer (1, 7, 2, 9) Scala>val bsorted = b.sorted (_<_) Bsorted:arraybuffer[int] = ArrayBuffer (1, 2, 7, 9)//tostring () method scala> Intarr.tostring () res94:string = [I@141aba8//mkstring () method scala> intarr.mkstring (",") res96:string = 1,2,3,4,5,6,7, 8,9,10 scala> intarr.mkstring ("<", ",", ">") res97:string = <1,2,3,4,5,6,7,8,9,10> 

7, ArrayBuffer Scaladoc analysis
Beginners often get confused when viewing Sacaladoc, without worrying, and as the learning progresses, the content in the API documentation will become clearer
Two examples are given below:
The parameter type passed in by the ++= method is a subclass of Traversableonce trait, which returns the updated Arraybuffer

Dropwhile passed in is a function that returns a Boolean type, dropwhile back to the Operation Arraybuffer

8. Multidimensional arrays
Like Java, multidimensional arrays are implemented by arrays.

//the first way to construct Val Metrix = array.ofdim[double] (3, 4)//3 row 4 column//access Element Metrix (row) (column) = 42// To create an irregular array, each line is not the same length Val triangle = new Array[array[int]] (Ten) for (I <-0 until triangle.length) trianglr (i) = new Ar Ray[int] (i+1)//At creation time scala> val Metrix = Array (Array (1, 2, 3), Array (2.3, 3.4), Array ("ASDF", "Asdfas") metrix:a
rray[array[_;: String with Double with Int]] = Array (Array (1, 2, 3), Array (2.3, 3.4), Arra y (asdf, Asdfas))//Print output array Scala> for (i <-Metrix) println (i.mkstring ("")) 1 2 3 2.3 3.4 asdf Asdfas//Output two-dimensional array for each value scala> for (i <-Metri X from = i; J <-from) println (j) 1 2 3 2.3 3.4 asdf Asdfas 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.