Second, the definition of an array
2.1 Definitions ordinary arrays
2.2 the definition of an array variable
3.1 Array general method
3.2 Variable Array common method
text
I. Introduction
A specified array elements are accessed through the index. Once the array defined, you can change its inner elements, a single length of the array can not be changed.
Second, the definition of an array
2.1 Definitions ordinary arrays
{ArrDemo Object DEF main (args: the Array [String]): Unit = { // definition of length 5, an integer type array var ARR = new new the Array [Int] (5 ) // defines a length of 5, any type array var of arr1 = new new the array [the Any] (. 5 ) // directly defined inside the array of content var arr2 is the array = (. 1, 2,. 3,. 4,. 5 ) } }
2.2 the definition of an array variable
import scala.collection.mutable.ArrayBuffer object ArrayDemo2 { def main(args: Array[String]): Unit = { var ab = ArrayBuffer[Int]() } }
Third, some methods array
3.1 Array general method
{ArrDemo Object DEF main (args: the Array [String]): Unit = { var arr2 is = the Array (. 1, 2,. 3,. 4,. 3 ) // Map method / array is an array mapping each element of some kind operation, (x: Int) => x * 2 is an anonymous function, x is each element of the array // e.g. var tmp = arr2.map (X => X * 2 ) Print (tmp.toBuffer) // an ArrayBuffer (2,. 4,. 6,. 8,. 6) Val words = the Array ( "Hello Hello Jim Tom Jerry Hello", "Hatano Hello" ) var TMP2 = words.map (X => x.split ( "" )) Print (TMP2 ( 0) .toBuffer, TMP2 (1) .toBuffer) // (ArrayBuffer(hello, tom, hello, jim, hello, jerry),ArrayBuffer(hello, Hatano)) // 扁平化操作,数组内的数组合并 var tmp3 = tmp2.flatten print(tmp3.toBuffer) // ArrayBuffer(hello, tom, hello, jim, hello, jerry, hello, Hatano) // flatMap方法是 map再flatten var arr3 = Array("hello tom hello jim hello jerry", "hello Hatano") arr3.flatMap(x => x.split(" ")) print(arr3.toBuffer) // ArrayBuffer(hello tom hello jim hello jerry, hello Hatano) } }
3.2 Variable array method
Import scala.collection.mutable.ArrayBuffer Object ArrayDemo2 { DEF main (args: the Array [String]): Unit = { var ab & = an ArrayBuffer [Int] () // Adds elements ab.append (. 1 ) ab.append ( 2 ) ab.append ( . 1 ) // Appends a single or multiple ab & + =. 4 ab & + = (5,5,3,2 ) // append an array ab & ++ the array (. 3,. 4 ) // at some position of the insertion element (index value) ab.insert (2,. 3 ) // array remove elements (index position) ab.remove (. 1) // change the array element (the index, the new value) ab.update (0,. 3 ) // Get variable array element Print (ab.toBuffer) } }