当前位置:网站首页>Kotlin arrays and collections (1) {create arrays, use arrays, use for in loops to traverse arrays, use array indexes, and multi-dimensional arrays}

Kotlin arrays and collections (1) {create arrays, use arrays, use for in loops to traverse arrays, use array indexes, and multi-dimensional arrays}

2022-06-25 10:22:00 Peach doesn't come out

【 The text content comes from 《 insane Kotlin The notes 》, The content of the code is original 】

1. Create array

[1]  Use arrayOf() function : In this way, there is no need to explicitly specify the length of the array , But you need to list each array element in turn plain . therefore , This method is actually equivalent to Java Static initialization of arrays . When you create an array in this way , Since the program has given each array element , therefore Kotlin You can infer the type of array elements . therefore , Don't need to arrayOf() Function to specify the type of array elements .

val intList = arrayOf(1, 2, 3)
for (i in intList) {
    println("intList has $i")
}


 Running results :
intList has 1
intList has 2
intList has 3

[2]  Use arrayOfNulls () function : In this way, you need to explicitly specify the length of the array , All array elements are initialized null , so This way is Java Dynamic initialization of arrays . When you create an array in this way , because Kotlin Cannot infer the type of an array element , So you need to be in rrayOfNull () Function to specify the type of array elements .

val stringList = arrayOfNulls<String>(3)
stringList[0] = "hello"
stringList[1] = " Hello "
stringList[2] = " Hello "
for (s in stringList) {
    println("stringList has $s")
}

 Running results :
stringList has hello
stringList has  Hello 
stringList has  Hello 

[3]  Use emptyArray() function : This method creates a length of 0 Empty array of . Because no array element is specified , So you need to use generics to specify the type of array elements .

val emptyList = arrayOfNulls<Int>(4)
for (e in emptyList){
    println("emptyList has $e")
}

 Running results :
emptyList has null
emptyList has null
emptyList has null
emptyList has null

[4]  Use Array(size: sichuan , init: (Int) -> ) Constructors : In this way, you need to explicitly specify the length of the array , And through Lambda Expression to dynamically calculate the value of each array element . This way is the original Java What you don't have .

val arr1 = Array(3) { "test" }
for (a1 in arr1) {
    println("arr1 has $a1")
}

 Running results :
arr1 has test
arr1 has test
arr1 has test

//Lambda In the expression it The unique formal parameter used to represent the expression 
val arr2 = Array(3) { (it + 2) * 4 }
for (a2 in arr2) {
    println("arr2 has $a2")
}

 Running results :
arr2 has 8
arr2 has 12
arr2 has 16

2. Using arrays

A common way to access arrays is to access array elements , Including assigning values to array elements and taking out the values of array elements . Array elements are accessed by following the array reference variable Square brackets ( [] ) Realized , In square brackets are the indexes of array elements . As mentioned earlier , Kotlin The square bracket operator is actually get(index) and set(index, value) Method , So when the program uses [i] When getting the value of an array element , It's actually a call get( index ) Method ; When using [index] Yes When assigning an array element , It's actually a call set(index , value) Method .

val intArray = intArrayOf(11, 22, 33, 44)
// Get the value of the first element 
println("intArray[0] = ${intArray[0]}")
// Reassign the value of the third element 
println("intArray[0] before is ${intArray[2]}")
intArray[2] = 333
println("intArray[0] after is ${intArray[2]}")

 Running results :
intArray[0] = 11
intArray[0] before is 33
intArray[0] after is 333

3.  Use for-in Loop through groups

Kotlin for-in The loop automatically iterates through each element of the array .

val forInArray = arrayOf(" How are you today ?", " Good day .", " That would be great .")
for (f in forInArray) {
    println(f)
}

 Running results :
 How are you today ?
 Good day .
 That would be great .

4. Use array index

[1] Use... When traversing an array using an index until arra size This way to create intervals .

[2] Kotlin The array of provides indices attribute , This property returns the index range of the array .( More convenient )

val indicesArray = arrayOf(1, 3, 5, 7, 9)
for (index1 in 0 until indicesArray.size) {
    println("[1]until test : ${indicesArray[index1]}")
}
for (index2 in indicesArray.indices) {
    println("[2]indices test : ${indicesArray[index2]}")
}

 Running results :
[1]until test : 1
[1]until test : 3
[1]until test : 5
[1]until test : 7
[1]until test : 9
[2]indices test : 1
[2]indices test : 3
[2]indices test : 5
[2]indices test : 7
[2]indices test : 9

5. Multidimensional arrays

The so-called multidimensional arrays are actually Dimension group , Just let the elements of the array be arrays again , Then the array becomes a multidimensional array .

val multiArray = arrayOfNulls<Array<String>>(4)
// Initializes the array element 
multiArray[0] = arrayOf(" Is it spring now ?", " Yes , It's spring now .")
multiArray[1] = arrayOf(" Is it summer now ?", " Yes , It's summer .")
multiArray[2] = arrayOf(" Is it autumn now ?", " Yes , It's autumn .")
multiArray[3] = arrayOf(" Is it winter now ?", " Yes , It's winter .")
for (firstIndex in multiArray.indices) {
    val detailString = StringBuilder("")
    for (secondIndex in multiArray[firstIndex]!!.indices) {
        detailString.append(multiArray[firstIndex]!![secondIndex])
        if (secondIndex != multiArray[firstIndex]!!.lastIndex) {
            detailString.append(" | ")
        }
    }
    println("$firstIndex | $detailString")
}

 Running results :
0 |  Is it spring now ? |  Yes , It's spring now .
1 |  Is it summer now ? |  Yes , It's summer .
2 |  Is it autumn now ? |  Yes , It's autumn .
3 |  Is it winter now ? |  Yes , It's winter .
That's the end of today !

原网站

版权声明
本文为[Peach doesn't come out]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200545120699.html