欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Kotlin 基础教程之数组容器

程序员文章站 2023-12-15 12:17:28
kotlin 基础教程之数组容器 arrays kotlin 标准库提供了arrayof()创建数组, **arrayof创建特定类型数组 val array...

kotlin 基础教程之数组容器

arrays

kotlin 标准库提供了arrayof()创建数组, **arrayof创建特定类型数组

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

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,需要进行类型转换

(intlist as abstractlist<int>).set(0, 30)
(nonnulls as java.util.arraylist).addall(arrayof("x", "y"))

maps

map是<key, value>容器, kotlin提供mapof创建map

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

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)

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

上一篇:

下一篇: