当前位置:网站首页>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
array1
No element , In line with expectations , It's an empty array , amount toarrayOfNulls<String>(0)
array2
Yes 3 Elements , All are nullarray3
Yes 10 Elements , They are subscripts 0~9 Of 2 Power , Conform to the initialization logicarray4
Yes 3 Elements , Consistent with the initialized element valuearray5
There's an element , Namelychar
Type 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!list2
andlist4
The principle is the same , Let's see.list2
Source 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 )
list5
andlist6
It's all doneMutableList
Interface , 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
边栏推荐
- Xctf mobile--rememberother problem solving
- 基于Linu开发的项目视频
- Unicode查询的官方网站
- Sword finger offer06 Print linked list from end to end
- Tianyi ty1208-z brush machine detailed tutorial (free to remove)
- 1-1 token
- Tensorflow binary installation & Failure
- [ArcGIS user defined script tool] vector file generates expanded rectangular face elements
- Application of ncnn neural network computing framework in orange school orangepi 3 lts development board
- Application of ncnn Neural Network Computing Framework in Orange Pi 3 Lts Development Board
猜你喜欢
电压环对 PFC 系统性能影响分析
If you can't learn, you have to learn. Jetpack compose writes an im app (II)
ncnn神经网络计算框架在香橙派OrangePi 3 LTS开发板中的使用介绍
Eureka自我保护
The future of cloud computing cloud native
Sword finger offer09 Implementing queues with two stacks
TOGAF认证自学宝典V2.0
【ManageEngine】IP地址扫描的作用
Alibaba is bigger than sending SMS (user microservice - message microservice)
LeetCode 0556. Next bigger element III - end of step 4
随机推荐
1-2 project technology selection and structure
Sword finger offer04 Search in two-dimensional array [medium]
Swift5.7 extend some to generic parameters
Keep learning swift
It feels great to know you learned something, isn‘t it?
Self made pop-up input box, input text, and click to complete the event.
Exploration of sqoop1.4.4 native incremental import feature
Attack and defense world mobile--ph0en1x-100
Approve iPad, which wants to use your icloud account
基于Linu开发的项目视频
并网-低电压穿越与孤岛并存分析
Tensorflow binary installation & Failure
Bert running error: attributeerror: module'tensorflow contrib. tpu' has no attribute 'InputPipelineConfig'
Take you to the installation and simple use tutorial of the deveco studio compiler of harmonyos to create and run Hello world?
RedHat5 安装Socket5代理服务器
4. Wireless in vivo nano network: electromagnetic propagation model and key points of sensor deployment
ORM use of node -serialize
flinksql是可以直接客户端建表读mysql或是kafka数据,但是怎么让它自动流转计算起来呢?
The latest version of blind box mall thinkphp+uniapp
Eureka self protection