簡單比較
- List : 有序、可重複
- Map : 鍵值對
- Set : 無序、不可重複
- Array : 有序、可重複、固定空間大小
List
fun main() {
val numbers = listOf(0, 3, 8, 4, 0, 5, 5, 8, 9, 2)
println("list: ${numbers} numbers[4]=${numbers[4]}")
println("sorted: ${numbers.sorted()}")
}
list: [0, 3, 8, 4, 0, 5, 5, 8, 9, 2] numbers[4]=0
sorted: [0, 0, 2, 3, 4, 5, 5, 8, 8, 9]
Map
fun main() {
val peopleAges = mutableMapOf(
"Fred" to 30,
"Ann" to 23
)
println(peopleAges)
peopleAges.put("Barbara", 42)
peopleAges["Joe"] = 51
println(peopleAges)
peopleAges["Fred"] = 31
println(peopleAges)
println("---")
peopleAges.forEach { print("${it.key} is ${it.value}, ") }
println()
println(peopleAges.map { "${it.key} is ${it.value}" }.joinToString(", ") )
println("---")
val filteredNames = peopleAges.filter { it.key.length < 4 }
println(filteredNames)
}
{Fred=30, Ann=23}
{Fred=30, Ann=23, Barbara=42, Joe=51}
{Fred=31, Ann=23, Barbara=42, Joe=51}
---
Fred is 31, Ann is 23, Barbara is 42, Joe is 51,
Fred is 31, Ann is 23, Barbara is 42, Joe is 51
---
{Ann=23, Joe=51}
Set
fun main() {
val numbers = listOf(0, 3, 8, 4, 0, 5, 5, 8, 9, 2)
val setOfNumbers = numbers.toSet()
println("set: ${setOfNumbers}")
println("contains 7: ${setOfNumbers.contains(7)}")
println("contains 1: ${setOfNumbers.contains(0)}")
println("-------")
val set1 = setOf(1,2,3) //不可變
val set2 = mutableSetOf(3,2,1) //可變
println("$set1 == $set2: ${set1 == set2}")
}
set: [0, 3, 8, 4, 5, 9, 2]
contains 7: false
contains 1: true
-------
[1, 2, 3] == [3, 2, 1]: true
Array
以 IntArray 為例
fun main() {
val array = IntArray(3)
array[0] = 1
println(array.joinToString())
for(n in array) {
println(n)
}
val array2 = Array(3){9}
println(array2.joinToString())
}
1, 0, 0
1
0
0
9, 9, 9
其他參考資料
0 comments:
張貼留言