当前位置:网站首页>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 162. 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 3333. 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 : 95. 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 .
边栏推荐
- Houdini图文笔记:Could not create OpenCL device of type (HOUDINI_OCL_DEVICETYPE)问题的解决
- Tutorial on installing SSL certificates in Microsoft Exchange Server 2007
- Mongodb's principle, basic use, clustering and partitioned clustering
- tokenizers>=0.11.1,!=0.11.3,<0.13 is required for a normal functioning of this module,
- Guiding principle - read source code
- [RPC] i/o model - Rector mode of bio, NiO, AIO and NiO
- Flutter Gaode map privacy compliance error
- Kotlin Foundation
- String longest common prefix
- [today in history] June 24: Netease was established; The first consumer electronics exhibition was held; The first webcast in the world
猜你喜欢

Flask blog practice - archiving and labeling of sidebar articles

【历史上的今天】6 月 24 日:网易成立;首届消费电子展召开;世界上第一次网络直播

Mongodb's principle, basic use, clustering and partitioned clustering

This is enough for request & response

How do wechat sell small commodity programs do? How to open wechat apps to sell things?

单片机开发---基于ESP32-CAM的人脸识别应用

P2P network core technology: Gossip protocol

How to apply for a widget on wechat how to get a widget on wechat

Floating window --- create an activity floating window (can be dragged)

Unique Wulin, architecture selection manual (including PDF)
随机推荐
SparseArray details
i++ 和 ++i的真正区别
Etcd tutorial - Chapter 4 etcd cluster security configuration
Get started quickly with jetpack compose Technology
Bitmap is converted into drawable and displayed on the screen
Shardingsphere proxy 4.1 Sous - base de données sous - table
Download the arm64 package of Debian on X86 computer
网络协议学习---LLDP协议学习
Identityserver4 definition concept
String longest common prefix
Redis (I) principle and basic use
申请多域名SSL证书的要求及注意事项
Houdini图文笔记:Your driver settings have been set to force 4x Antialiasing in OpenGL applications问题的解决
Force buckle -104 Maximum depth of binary tree
The real difference between i++ and ++i
Macro application connector\
【历史上的今天】6 月 24 日:网易成立;首届消费电子展召开;世界上第一次网络直播
Basic usage and principle of schedulemaster distributed task scheduling center
‘Flutter/Flutter. h‘ file not found
How do wechat sell small commodity programs do? How to open wechat apps to sell things?