Three, Scala array related operations

1. Fixed-length array

val nums = new Array[Int](10)//10个整数的数组,所有元素初始化为0
val s = Array("hello","world")//长度为2,类型由Scala自行推断,因为给了初始值,所以不用写new
s(0) = "google" //元素的访问使用()而不是[]

2. Variable length array: array buffer

For variable length arrays, the equivalent structure in Scala isArrayBuffer

import scala.collection.mutable.ArrayBuffer
val b = ArrayBuffer[Int]()//或者不写()改用new ,此处表示一个空的数组缓冲,准备存放整数
b+=1	//使用+=在尾端添加元素
b+=(1,2,3,4,5,6)	//在尾端添加多个元素,以括号包起来
b++=Array(8,12,13)	//可以用++=操作符在后面追加任何集合

b.trimEnd(5)	//移除最后5个元素

b.insert(2,6)	//在下标2之前插入
b.insert(2,1,2,3,1,3)	//在下标2前插入多个元素

b.remove(2)	//移除下标为2的元素
b.remove(2,3)//移除下标2开始的3个元素

b.toArray(1,1,2)	//此做法为当不确定自己要构建的Array要装多少个元素时,可以先使用ArrayBuffer,然后在转换为Array
//同理,也可以使用a.toBuffer将一个数组a转化为一个数组缓冲

Note: Inserting or removing elements at any position is not efficient

3. Traverse arrays and array buffers

Use for spirit ring to traverse array or array bufferfor(i <- 区间)

for(i<- 0 until a.length)//until类似于to,但是不包含a.length
	println(s"$i:${a(i)}")//s开头,字符串可以包含表达式但不能有格式化指令,拓展:row开头不会求值转义字符
设置每一步的步长
0 until a.length by 2//得到的结果是Range(0,2,4,6,8)

If you want to start the traversal at the heavy end, set the step size to -1

0 until a.length by -1

Do not use array subscripts, directly access array elements

for(elem <- a)
	println(elem)

4. Array conversion

In Scala, it is very simple to convert it in some way. These conversion operations do not modify the original array, but create a completely new array.

val a = Array(2,3,5,7,11)
val result = for(elem<-a) yield 2 *elem

You can also add guards in the loop

for(elem <-a if elem % 2 ==0)	yield 2*elem

But usually another way of writing

a.filter(_ % 2==0).map(2 * _)//可以用{}代替()

As mentioned above, a new array is created. For example, if you want to modify the original array (you can use indices to get the subscript sequence of the array )

val positionToRemove = for(i<-a.indices if a(i) <0 )yields i
for(i <-positionToRemove.reverse) a.remove(i)
//另一种更好的方式是将要的元素复制到前面,然后截取指定个数的元素

5. Commonly used algorithms

max,min,sum,sorted,sortedWith(),qucikSort()
mkString("<",",",">")//分别表示前缀,分隔符,后缀

6. Interpret Scaladoc

Don't explain too much for now

7. Multidimensional array

Create an array of type Array[Array[Double]]

val matrix = Array.ofDim[Double](3,4)//三行四列
//访问元素的方式:martix(row)(column) = 42

To create an irregular array

val trangle = Array[Array[Int]](10)
for(i<-trangle.indices)
	trangle(i) = new Array[Int](i+1)

8. Interoperability with Java

Java's String[] array can be passed into a method that expects Java's Object[] array, but Scala does not allow such automatic conversion.
If you want to call a method with an Object[] array, you need to manually convert the type

val a = Array("dadas","dasdad","assda","dadadas")
java.util.Arrays.binarySearch(a.asInstanceOf[Array[Object]],"breef")

This part is clear

Guess you like

Origin blog.csdn.net/Cxf2018/article/details/109411368