当前位置:网站首页>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 .

边栏推荐
- 【动态规划】—— 数字三角形
- Comparison and evaluation of digicert and globalsign single domain ov SSL certificates
- [paper reading | depth] role based network embedding via structural features reconstruction with degree regulated
- Download the arm64 package of Debian on X86 computer
- BUG-00x bug description + resolve ways
- OpenCV学习(一)---环境搭建
- Flutter Gaode map privacy compliance error
- Experience in writing C
- WPF Prism框架
- 链表 删除链表中的节点
猜你喜欢
Flask blog practice - archiving and labeling of sidebar articles
Free platform for wechat applet making, steps for wechat applet making
[today in history] June 24: Netease was established; The first consumer electronics exhibition was held; The first webcast in the world
之前字符串反转的题目
字符串 最长公共前缀
Minio基本使用与原理
【历史上的今天】6 月 24 日:网易成立;首届消费电子展召开;世界上第一次网络直播
OpenCV学习(二)---树莓派上安装opencv
The real difference between i++ and ++i
Get started quickly with jetpack compose Technology
随机推荐
JS tool function, self encapsulating a throttling function
Jetpack compose layout (III) - custom layout
[paper reading | deep reading] line: large scale information network embedding
MySQL source code reading (II) login connection debugging
Difference between malloc and calloc
Cocopod error failed: undefined method `map 'for nil:nilclass
The left sliding menu +menu item icon is grayed out
MySQL create given statement
Jetpack compose layout (I) - basic knowledge of layout
【论文阅读|深度】Role-based network embedding via structural features reconstruction with degree-regularized
依赖属性、依赖附加属性以及类型转换
单片机开发---基于ESP32-CAM的人脸识别应用
[today in history] June 24: Netease was established; The first consumer electronics exhibition was held; The first webcast in the world
Modbus protocol and serialport port read / write
How do wechat applets make their own programs? How to make small programs on wechat?
[paper reading | depth] role based network embedding via structural features reconstruction with degree regulated
Jetpack compose layout (II) - material components and layout
SQL to object thinking vs SQL of object thinking
链表 删除链表中的节点
OpenCV学习(二)---树莓派上安装opencv