学习到Kotlin的数组和集合,这里做个记录。
数组Array
Kotlin中数组也是个容器,提供了不同的类型有:ByteArray
, CharArray
, ShortArray
, IntArray
, LongArray
, BooleanArray
, FloatArray
,DoubleArray
,一大堆,这里不一一介绍,用法都差不多,只是带类型的数组只能装指定类型。
初始化
//初始化一个空的数组,实际上它是大小为0继承arrayOfNulls的数组
var array1 = emptyArray<String>()
//初始化一个空的数组,需要传入数组大小
var array2 = arrayOfNulls<String>(3)
//初始化一个指定大小数组,第一个参数是size,第二个参数是生成逻辑的函数,
// 相当于java中遍历数组,给每个下标为k的数组赋值array2[k] = k * k;
var array3 = Array(10) { k -> k * k}
//初始化一个多数据类型的数组
var array4 = arrayOf("1",2,3)
//初始化一个特定数据类型-字符类型的数组
var array5 = charArrayOf('d')
我们打印一下初始化后的数组,看看初始化的结果:
"/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
可以看到
-
array1
并没有元素,符合预期,它是一个空数组,相当于arrayOfNulls<String>(0)
-
array2
有3个元素,都是null -
array3
有10个元素,分别是下标0~9的2次方,符合初始化逻辑 -
array4
有3个元素,和初始化的元素值一致 -
array5
有一个元素,就是char
类型的d
数组的元素扩充:plus
和Java
一样,Kotlin
的array默认大小就是你给定的,初始化是0就是0,初始化是100它就是100,但是查看源码,你会发现kotlin还是提供了一个添加元素的api,plus
方法
/**
* 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方法注释上说,返回一个包含原来数组所有元素的数组,实际上就是将来原来的数组拷贝了一下,并且长度+1,然后给数组添加新的元素,虽然性能上不好,但是可以很方便的添加元素。这里注意的是,方法返回的是一个新的数组,因此需要接收它,否则添加是不成功的,我们用array4
示范下:
//初始化一个多数据类型的数组
var array4 = arrayOf("1",2,3)
array4.plus("1")
for (i in array4){
println(i)
}
打印结果是:
1
2
3
Process finished with exit code 0
现在我们稍微改下代码:
//初始化一个多数据类型的数组
var array4 = arrayOf("1",2,3)
//array4.plus("4")
array4 = array4.plus("4")
for (i in array4){
println(i)
}
此时的打印结果:
1
2
3
4
Process finished with exit code 0
数组元素的填充:fill
array提供了fill
函数,给原有的数组填充数组(如果原来有数据将会被覆盖),操作示范:
//初始化一个多数据类型的数组
var array4 = arrayOf("1",2,3)
//往数组里填入数据"4",fromIndex 0 toIndex 2,从下标0到2,不包含2
array4.fill("4",0,2)
for (i in array4){
println(i)
}
结果可以猜得到:
4
4
3
Process finished with exit code 0
我们来看看fill
方法的源码
/**
* Fills original array with the provided value.
*/
public fun <T> Array<T>.fill(element: T, fromIndex: Int = 0, toIndex: Int = size): Unit {
//这里调用了Java的fill操作
java.util.Arrays.fill(this, fromIndex, toIndex, element)
}
直接看上面的函数还看不出来原理,但是我们可以看到,他调用的是Java的fill方法,继续查看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;
}
很简单的操作,就是遍历赋值
集合List
Kotlin集合和Java的集合类似,都实现了Collection
接口,Kotlin集合分为
- 不可变集合(immutable)
- 可变集合(mutable)
初始化
//通过元素初始化一个不可变集合
var list1 = listOf("aaa", "bbb","ccc","dddd")
//初始化一个空的不可变集合
var list2 = emptyList<String>()
//初始化一个过滤空元素的不可变集合
var list3 = listOfNotNull(1,null)
//初始化一个空的不可变集合,和list2是一样的
val list4:List<String> = listOf()
//创建一个带元素的可变集合
var list5 = mutableListOf("22","33")
//创建一个空的arrayList,它也可变集合
var list6 = arrayListOf<String>()
这里不一一打印它们的元素了,需要注意的是
-
list3
,它只有一个元素是1,集合大小也是1,因为过滤调了null! -
list2
和list4
原理一样,我们看看list2
源码
/**
* 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
可以看到它是返回一个空的只读list,并且在JVM
中是可序列化的(在android项目里Kotlin
现阶段还是寄生在JVM
平台的,所有的Kotlin
源代码都会被编译成class文件)
-
list5
和list6
都实现了MutableList
接口,源码可以看出来它们的等效的
/**
* 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()
实际上也是调用ArrayList
集合元素的扩充
不可变集合用plus
不可变集合,按理说是不能扩充元素的,因为他们只读(read—only)。但是你想要添加元素也行,通过调用plus
方法,其原理和数组一样,都是创建新的集合,长度+1,并不是真的可变,这里的plus
方法是个运算符重载函数,因此你也可以用"+"来添加
//通过元素初始化一个不可变集合
var list1 = listOf("aaa", "bbb","ccc","dddd")
//通过plus添加
list1 = list1.plus("fff")
//通过+添加
list1 += "eeee"
//打印
for (i in list1){
println(i)
}
结果是:
aaa
bbb
ccc
dddd
fff
eeee
Process finished with exit code 0
可变的集合用add
这个简单,直接add
进来就是了,和Java
的arraylist
使用一样。有的人会问了,这里能不能用plus
呢,答案是可以用,但是不能增加元素,和不可变集合一样,我们来看看:
//创建一个带元素的可变集合
var list5 = mutableListOf("22","33")
//使用plus添加
list5.plus("444")
//使用add添加
list5.add("r3r3")
//打印
for (i in list5){
println(i)
}
打印结果:
22
33
r3r3
Process finished with exit code 0
这里的plus
效果和不可变数组以及不可变集合里是一样的,非要使用需要对集合重新赋值,参考不可变集合的使用,这里强烈不推荐使用
集合元素的填充
填充和Java
的List
也是极其相似,用法是一样一样的。无论可变不可变集合都一样!
数组和集合的相互转换
数组转集合:toList()
val array1 = arrayOf(1,2,3)
//数组转集合
var list7 = array1.toList()
println("list7 = $list7")
打印结果:
list7 = [1, 2, 3]
Process finished with exit code 0
集合转数组:toTypedArray()
//通过元素初始化一个不可变集合
var list1 = listOf("aaa", "bbb","ccc","dddd")
//集合转数组
val array1 = list1.toTypedArray()
for (temp in array1)
println(temp)
打印结果:
aaa
bbb
ccc
dddd
Process finished with exit code 0
总结
Kotlin
的array
和list
当然还有一些别的方法,大家可以自己去看源码或api,集合这里没有讲到map
和set
,有机会再补充