Kotlin 基础教程之数组容器

时间:2022-09-27 13:44:33

Kotlin 基础教程之数组容器

Arrays

Kotlin 标准库提供了arrayOf()创建数组, **ArrayOf创建特定类型数组

?
1
2
3
4
5
6
7
val array = arrayOf(1, 2, 3)
val countries = arrayOf("UK", "Germany", "Italy")
val numbers = intArrayOf(10, 20, 30)
val array1 = Array(10, { k -> k * k })
val longArray = emptyArray<Long>()
val studentArray = Array<Student>(2)
studentArray[0] = Student("james")

和Java不一样,Kotlin 的数组是容器类, 提供了 ByteArray, CharArray, ShortArray, IntArray, LongArray, BooleanArray, FloatArray, and DoubleArray。

Lists

List是有序容器,Kotlin 标准库通过listOf()创建list

?
1
2
3
4
5
val intList: List<Int> = listOf(20, 5, 10)
val emptyList: List<String> = emptyList<String>()
val nonNulls: List<String> = listOfNotNull<String>(null, "a", "b", "c")
 
val doubleList: ArrayList<Double> = arrayListOf(84.88, 100.25, 999.99)

其中,intList, emptyList, nonNulls是只读的实例,要修改这些list,需要进行类型转换

?
1
2
(intList as AbstractList<Int>).set(0, 30)
(nonNulls as java.util.ArrayList).addAll(arrayOf("x", "y"))

Maps

Map是<key, value>容器, Kotlin提供mapOf创建map

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
val value = map.get(b)
 
val states: MutableMap<String, String>= mutableMapOf("AL" to "Alabama",
    "AK" to "Alaska", "AZ" to "Arizona")
 
val customers: java.util.HashMap<Int, Customer> = hashMapOf(1 to
    Customer("Dina", "Kreps", 1), 2 to Customer("Andy", "Smith", 2))
 
val linkedHashMap: java.util.LinkedHashMap<String, String> =
    linkedMapOf("red" to "#FF0000","azure" to "#F0FFFF","white" to "#FFFFFF")
 
val sortedMap: java.util.SortedMap<Int, String> = sortedMapOf(4 to "d",
    1 to "a", 3 to "c", 2 to "b")

Sets

Set是没有重复项的容器, Kotlin提供setOf创建Set

?
1
2
3
4
5
val intSet: Set<Int> = setOf(1, 21, 21, 2, 6, 3, 2) //1,21,2,6,3
val hashSet: java.util.HashSet<Book> = hashSetOf(
    Book("Jules Verne", "Around the World in 80 Days Paperback", 2014, "978-1503215153"),
    Book("Jules Verne", "Around the World in 80 Days Paperback", 2014, "978-1503215153"))
val sortedIntegers: java.util.TreeSet<Int> = sortedSetOf(11, 0, 9, 11, 9, 8)

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://www.jianshu.com/p/a952c11975db