Java中,集合是最常用的数据结构。List、Map、Set三大集合类,在Kotlin中也有对应的
1 List
1.1 创建List集合
创建List集合的方式有listOf、mutableListOf,其中listOf不具备写操作,只能初始化其内容不可改变;mutableListOf具备写操作的能力,可以通过add添加到集合中元素
var mutableListOf = mutableListOf<Int>()
mutableListOf.add(1)
mutableListOf.add(2)
mutableListOf.add(3)
var listOf = listOf(1, 2, 3)
listOf.add() //不能执行写操作
通过emptyList可以创建一个空集合
var emptyList = emptyList<Int>()
1.2 集合的遍历
通过in、forEach遍历集合,获取集合中的全部元素
for (item in mutableListOf){
println(item)
}
mutableListOf.forEach {
println(it)
}
如果想通过index来获取集合的元素,可以调用集合的indices
for (index in mutableListOf.indices){
println("索引$index 对应的元素 ${mutableListOf.get(index)}")
}
2 Map
2.1 创建Map
同List一样,创建Map同样是使用mapOf、mutableMapOf创建,想要操作Map集合,就要使用mutableMapOf,使用put方法来插入map集合
var mutableMapOf = mutableMapOf<String, Int>()
mutableMapOf.put("kk",12)
mutableMapOf.put("ll",13)
mutableMapOf.put("mm",14)
2.2 Map的遍历
for (key in mutableMapOf.keys){
println("$key 对应的value ${mutableMapOf.get(key)}")
}
通过keys获取当前Map的全部Key集合,然后根据Key从Map中取出Value
3 Set
Set和List的使用方式一致,但是Set中不存在重复的元素
4 创建数组
如果声明有数组大小的数组,可使用ByteArray,IntArray …
val byteArray = ByteArray(bufferSize)