当前位置:网站首页>Simple use and precautions of kotlin's array array and set list
Simple use and precautions of kotlin's array array and set list
2022-07-03 12:43:00 【liuhaha1015】
Original address :Kotlin Array of array And collection list Simple use and precautions - Simple books
Record learning ↓↓↓
Array Array
Kotlin The array in is also a container , Different types are provided :ByteArray, CharArray, ShortArray, IntArray, LongArray, BooleanArray, FloatArray,DoubleArray, A lot of , I won't introduce you here , The usage is almost the same , Only arrays with types can only contain specified types .
initialization
// Initialize an empty array , In fact, its size is 0 Inherit arrayOfNulls Array of
var array1 = emptyArray<String>()
// Initialize an empty array , You need to pass in the array size
var array2 = arrayOfNulls<String>(3)
// Initialize an array of specified size , The first parameter is size, The second parameter is the function that generates the logic ,
// amount to java Traversing the array , Subscript each with k Array assignment of array2[k] = k * k;
var array3 = Array(10) { k -> k * k}
// Initialize an array of multiple data types
var array4 = arrayOf("1",2,3)
// Initialize a specific data type - An array of character types
var array5 = charArrayOf('d')
Let's print the initialized array , Look at the result of initialization :
"/Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java" -ea -Didea.test.cyclic.buffer.size=1048576 -Didea.launcher.port=49730 "-Didea.launcher.bin.path=/Applications/Android Studio.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath "/Applications/Android Studio.app/Contents/lib/idea_rt.jar:/Applications/Android Studio.app/Contents/plugins/junit/lib/junit-rt.jar:/Applications/Android Studio.app/Contents/plugins/junit/lib/junit5-rt.jar:/Users/kingnewspring/Library/Android/sdk/platforms/android-27/data/res:/Users/kingnewspring/Downloads/KotlinTest/app/build/intermediates/classes/debug:/Users/kingnewspring/Downloads/KotlinTest/app/build/tmp/kotlin-classes/debug:/Users/kingnewspring/Downloads/KotlinTest/app/build/generated/res/rs/debug:/Users/kingnewspring/Downloads/KotlinTest/app/build/generated/res/resValues/debug:/Users/kingnewspring/Downloads/KotlinTest/app/build/tmp/kotlin-classes/debugUnitTest:/Users/kingnewspring/.gradle/caches/modules-2/files-2.1/android.arch.lifecycle/common/1.1.0/edf3f7bfb84a7521d0599efa3b0113a0ee90f85/common-1.1.0.jar:/Users/kingnewspring/.gradle/caches/modules-2/files-2.1/com.android.support/support-annotations/27.1.1/39ded76b5e1ce1c5b2688e1d25cdc20ecee32007/support-annotations-27.1.1.jar:/Users/kingnewspring/.gradle/caches/transforms-1/files-1.1/animated-vector-drawable-27.1.1.aar/1be6be214d4bf5183a3327597856db9a/jars/classes.jar:/Users/kingnewspring/.gradle/caches/transforms-1/files-1.1/support-compat-27.1.1.aar/5318e651055d11149bff8ecc6ee849b7/jars/classes.jar:/Users/kingnewspring/.gradle/caches/transforms-1/files-1.1/support-compat-27.1.1.aar/5318e651055d11149bff8ecc6ee849b7/res:/Users/kingnewspring/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-jdk7/1.2.50/3811b225f9a22abf4f9d8a6f81adef0ba78a3c5/kotlin-stdlib-jdk7-1.2.50.jar:/Users/kingnewspring/.gradle/caches/transforms-1/files-1.1/viewmodel-1.1.0.aar/80fe4b8d90eafb67cf217b6d35b9d09e/jars/classes.jar:/Users/kingnewspring/.gradle/caches/transforms-1/files-1.1/support-vector-drawable-27.1.1.aar/c608acaab2dec891d8b39f2483c7e51b/jars/classes.jar:/Users/kingnewspring/.gradle/caches/transforms-1/files-1.1/support-core-ui-27.1.1.aar/18f9fb381d82d8ce4a1d4bda82e765cf/jars/classes.jar:/Users/kingnewspring/.gradle/caches/transforms-1/files-1.1/support-core-ui-27.1.1.aar/18f9fb381d82d8ce4a1d4bda82e765cf/res:/Users/kingnewspring/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-common/1.2.50/6b19a2fcc29d34878b3aab33fd5fcf70458a73df/kotlin-stdlib-common-1.2.50.jar:/Users/kingnewspring/.gradle/caches/transforms-1/files-1.1/support-core-utils-27.1.1.aar/dc31deadc75ff47a72c687e48f9669d7/jars/classes.jar:/Users/kingnewspring/.gradle/caches/transforms-1/files-1.1/constraint-layout-1.1.3.aar/0b9e57814d1dfbd5924ef90766162087/res:/Users/kingnewspring/.gradle/caches/transforms-1/files-1.1/constraint-layout-1.1.3.aar/0b9e57814d1dfbd5924ef90766162087/jars/classes.jar:/Users/kingnewspring/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.2.50/66d47b004c5b8a1d2d1df9e463187390ed741316/kotlin-stdlib-1.2.50.jar:/Users/kingnewspring/.gradle/caches/modules-2/files-2.1/org.jetbrains/annotations/13.0/919f0dfe192fb4e063e7dacadee7f8bb9a2672a9/annotations-13.0.jar:/Users/kingnewspring/.gradle/caches/transforms-1/files-1.1/support-fragment-27.1.1.aar/52d6725357d2b27fdf8d861bfd464aa4/jars/classes.jar:/Users/kingnewspring/.gradle/caches/modules-2/files-2.1/junit/junit/4.12/2973d150c0dc1fefe998f834810d68f278ea58ec/junit-4.12.jar:/Users/kingnewspring/.gradle/caches/transforms-1/files-1.1/runtime-1.1.0.aar/6c59003f6d713b57600f30ff3d7250e3/jars/classes.jar:/Users/kingnewspring/.gradle/caches/modules-2/files-2.1/org.hamcrest/hamcrest-core/1.3/42a25dc3219429f0e5d060061f71acb49bf010a0/hamcrest-core-1.3.jar:/Users/kingnewspring/.gradle/caches/transforms-1/files-1.1/appcompat-v7-27.1.1.aar/a88341bae42c2eb22d3a232380966a18/res:/Users/kingnewspring/.gradle/caches/transforms-1/files-1.1/appcompat-v7-27.1.1.aar/a88341bae42c2eb22d3a232380966a18/jars/classes.jar:/Users/kingnewspring/.gradle/caches/transforms-1/files-1.1/livedata-core-1.1.0.aar/9683c5714c058ad2ce152c04a0e3a19d/jars/classes.jar:/Users/kingnewspring/.gradle/caches/modules-2/files-2.1/android.arch.core/common/1.1.0/8007981f7d7540d89cd18471b8e5dcd2b4f99167/common-1.1.0.jar:/Users/kingnewspring/.gradle/caches/modules-2/files-2.1/com.android.support.constraint/constraint-layout-solver/1.1.3/bde0667d7414c16ed62d3cfe993cff7f9d732373/constraint-layout-solver-1.1.3.jar:/Users/kingnewspring/.gradle/caches/transforms-1/files-1.1/runtime-1.1.0.aar/e51aad556365d772d1b760355b0ea1f6/jars/classes.jar:/Users/kingnewspring/Downloads/KotlinTest/app/build/intermediates/sourceFolderJavaResources/test/debug:/Users/kingnewspring/Downloads/KotlinTest/app/build/intermediates/sourceFolderJavaResources/debug:/Users/kingnewspring/Downloads/KotlinTest/app/build/generated/mockable-android-27.v3.jar" com.intellij.rt.execution.application.AppMainV2 com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 com.example.kingnewspring.kotlintest.ExampleUnitTest
arra2:null
arra2:null
arra2:null
arra3:0
arra3:1
arra3:4
arra3:9
arra3:16
arra3:25
arra3:36
arra3:49
arra3:64
arra3:81
arra4:1
arra4:2
arra4:3
arra5:d
Process finished with exit code 0
You can see
array1No element , In line with expectations , It's an empty array , amount toarrayOfNulls<String>(0)array2Yes 3 Elements , All are nullarray3Yes 10 Elements , They are subscripts 0~9 Of 2 Power , Conform to the initialization logicarray4Yes 3 Elements , Consistent with the initialized element valuearray5There's an element , NamelycharType of d
Element expansion of array :plus
and Java equally ,Kotlin Of array The default size is what you give , Initialization is 0 Namely 0, Initialization is 100 It is 100, But look at the source code , You'll find that kotlin It also provides a way to add elements api,plus Method
/**
* Returns an array containing all elements of the original array and then the given [element].
*/
public actual operator fun <T> Array<T>.plus(element: T): Array<T> {
val index = size
val result = java.util.Arrays.copyOf(this, index + 1)
result[index] = element
return result
}
plus The method notes say , Returns an array containing all the elements of the original array , In fact, the original array will be copied in the future , And the length +1, Then add new elements to the array , Although the performance is not good , But you can easily add elements . Here's the thing to notice , Method returns a new array , So you need to receive it , Otherwise, the addition will not succeed , We use it array4 Under demonstration :
// Initialize an array of multiple data types
var array4 = arrayOf("1",2,3)
array4.plus("1")
for (i in array4){
println(i)
}
The printout is :
1
2
3
Process finished with exit code 0
Now let's change the code a little :
// Initialize an array of multiple data types
var array4 = arrayOf("1",2,3)
//array4.plus("4")
array4 = array4.plus("4")
for (i in array4){
println(i)
}
The print result at this time :
1
2
3
4
Process finished with exit code 0
Padding of array elements :fill
array Provides fill function , Fill the original array ( If the original data will be overwritten ), Operation demonstration :
// Initialize an array of multiple data types
var array4 = arrayOf("1",2,3)
// Fill the array with data "4",fromIndex 0 toIndex 2, From the subscript 0 To 2, It doesn't contain 2
array4.fill("4",0,2)
for (i in array4){
println(i)
}
The result can be guessed :
4
4
3
Process finished with exit code 0
Let's see fill Method source code
/**
* Fills original array with the provided value.
*/
public fun <T> Array<T>.fill(element: T, fromIndex: Int = 0, toIndex: Int = size): Unit {
// Here we call Java Of fill operation
java.util.Arrays.fill(this, fromIndex, toIndex, element)
}
Looking directly at the above function, you can't see the principle , But we can see that , What he's calling is Java Of fill Method , Keep looking at java.util.Arrays.fill
/**
* Assigns the specified Object reference to each element of the specified
* range of the specified array of Objects. The range to be filled
* extends from index <tt>fromIndex</tt>, inclusive, to index
* <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the
* range to be filled is empty.)
*
* @param a the array to be filled
* @param fromIndex the index of the first element (inclusive) to be
* filled with the specified value
* @param toIndex the index of the last element (exclusive) to be
* filled with the specified value
* @param val the value to be stored in all elements of the array
* @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>
* @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or
* <tt>toIndex > a.length</tt>
* @throws ArrayStoreException if the specified value is not of a
* runtime type that can be stored in the specified array
*/
public static void fill(Object[] a, int fromIndex, int toIndex, Object val) {
rangeCheck(a.length, fromIndex, toIndex);
for (int i = fromIndex; i < toIndex; i++)
a[i] = val;
}
Very simple operation , Is to traverse the assignment
aggregate List
Kotlin The collection and Java The set of is similar to , It's all done Collection Interface ,Kotlin The set is divided into
- Immutable set (immutable)
- Variable set (mutable)
initialization
// Initialize an immutable set through elements
var list1 = listOf("aaa", "bbb","ccc","dddd")
// Initialize an empty immutable set
var list2 = emptyList<String>()
// Initialize an immutable set that filters empty elements
var list3 = listOfNotNull(1,null)
// Initialize an empty immutable set , and list2 It's the same
val list4:List<String> = listOf()
// Create a variable set with elements
var list5 = mutableListOf("22","33")
// Create an empty arrayList, It is also a variable set
var list6 = arrayListOf<String>()
Here we won't print their elements one by one , It should be noted that
list3, It has only one element 1, The set size is also 1, Because the filter is adjusted null!list2andlist4The principle is the same , Let's see.list2Source code
/**
* Returns an empty read-only list. The returned list is serializable (JVM).
* @sample samples.collections.Collections.Lists.emptyReadOnlyList
*/
public fun <T> emptyList(): List<T> = EmptyList
You can see that it returns an empty read-only list, And in JVM Is serializable ( stay android In the project Kotlin At this stage, it is still parasitic JVM Platform , be-all Kotlin The source code will be compiled into class file )
list5andlist6It's all doneMutableListInterface , The source code can see their equivalence
/**
* Returns a new [MutableList] with the given elements.
* @sample samples.collections.Collections.Lists.mutableList
*/
public fun <T> mutableListOf(vararg elements: T): MutableList<T> =
if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))
mutableListOf() It's actually calling ArrayList
Expansion of set elements
For immutable sets plus
Immutable set , Logically, elements cannot be extended , Because they read only (read—only). But you can also add elements if you want , By calling plus Method , Its principle is the same as array , It's all about creating new collections , length +1, It's not really changeable , there plus Method is an operator overloaded function , So you can also use "+" To add
// Initialize an immutable set through elements
var list1 = listOf("aaa", "bbb","ccc","dddd")
// adopt plus add to
list1 = list1.plus("fff")
// adopt + add to
list1 += "eeee"
// Print
for (i in list1){
println(i)
}
The result is :
aaa
bbb
ccc
dddd
fff
eeee
Process finished with exit code 0
Variable sets are used add
This simple , direct add Just come in , and Java Of arraylist Use the same . Some people will ask , Can I use it here plus Well , The answer is that you can use , But you can't add elements , Like immutable sets , Let's see :
// Create a variable set with elements
var list5 = mutableListOf("22","33")
// Use plus add to
list5.plus("444")
// Use add add to
list5.add("r3r3")
// Print
for (i in list5){
println(i)
}
Print the results :
22
33
r3r3
Process finished with exit code 0
there plus The effect is the same as that in immutable arrays and immutable sets , If you want to use it, you need to reassign the set , Use of reference immutable sets , It is strongly not recommended to use
Filling of set elements
Filling and Java Of List It is also very similar , The usage is the same . It's the same for both mutable and immutable sets !
The transformation between arrays and sets
Array to set :toList()
val array1 = arrayOf(1,2,3)
// Array to set
var list7 = array1.toList()
println("list7 = $list7")
Print the results :
list7 = [1, 2, 3]
Process finished with exit code 0
Set array :toTypedArray()
// Initialize an immutable set through elements
var list1 = listOf("aaa", "bbb","ccc","dddd")
// Set array
val array1 = list1.toTypedArray()
for (temp in array1)
println(temp)
Print the results :
aaa
bbb
ccc
dddd
Process finished with exit code 0
边栏推荐
- Sword finger offer03 Repeated numbers in the array [simple]
- 剑指Offer04. 二维数组中的查找【中等】
- Cloud Computing future - native Cloud
- CNN MNIST handwriting recognition
- Xctf mobile--app1 problem solving
- Ali & ant self developed IDE
- T430 toss and install OS majave 10.14
- 4. 无线体内纳米网:电磁传播模型和传感器部署要点
- What is more elegant for flutter to log out and confirm again?
- GCN thinking - word2vec directly calculates text classification
猜你喜欢

Prompt unread messages and quantity before opening chat group
![[ArcGIS user defined script tool] vector file generates expanded rectangular face elements](/img/39/0b31290798077cb8c355fbd058e4d3.png)
[ArcGIS user defined script tool] vector file generates expanded rectangular face elements

最新版抽奖盲盒运营版

低代码平台国际化多语言(i18n)技术方案

Togaf certification self-study classic v2.0

Low code platform international multilingual (I18N) technical solution

Drop down refresh conflicts with recyclerview sliding (swiperefreshlayout conflicts with recyclerview sliding)

公纵号发送提示信息(用户微服务--消息微服务)

4. 无线体内纳米网:电磁传播模型和传感器部署要点

云计算未来 — 云原生
随机推荐
Official website of Unicode query
initial、inherit、unset、revert和all的区别
阿里 & 蚂蚁自研 IDE
社交社区论坛APP超高颜值UI界面
阿里大于发送短信(用户微服务--消息微服务)
The latest version of blind box mall thinkphp+uniapp
The difference between lambda and anonymous inner class
[ArcGIS user defined script tool] vector file generates expanded rectangular face elements
Sword finger offer10- I. Fibonacci sequence
Xctf mobile--app3 problem solving
Dix règles de travail
init. RC service failed to start
Idea packages the web project into a war package and deploys it to the server to run
Everything comes to him who waits
2.8 overview of ViewModel knowledge
Public and private account sending prompt information (user microservice -- message microservice)
十條職場規則
01_ Using the concurrent tool class library, is thread safety safe
Adult adult adult
强大的头像制作神器微信小程序