Quantcast
Channel: CSDN博客移动开发推荐文章
Viewing all articles
Browse latest Browse all 5930

Kotlin数组容器

$
0
0

Arrays

Kotlin 标准库提供了arrayOf()创建数组,所以一般后缀是arrayOf()的,都可以找到相应的数组类型,以下是常用的几种,还有很多可以看看官方API

//普通数组
val array = arrayOf(1, 2, 3)
//字符串数组
val strings = arrayOf("cn", "fr", "it")
//int数组
val numbers = intArrayOf(10, 20, 30)
//运算数组
val operationArray = Array(10, { k -> k * k })
//空数组
val longArray = emptyArray<Long>()
//bean数组
val studentArray = Array<MyBean>(2)
studentArray[0] = MyBean("xiaoming")

List

List是有序容器,通过listOf创建,不过创建出来好像是只读序列,读写数组需要用MutableList显式修饰

fun list() {
    var list = listOf<String>()
    var notNull = listOfNotNull("1", "2", "3")
    var nonNulls: List<String> = listOfNotNull<String>(null, "a", "b", "c")

    var intList: List<Int> = listOf(1, 2, 3)
    var emptyList: List<String> = emptyList<String>()
    var doubleList: ArrayList<Double> = arrayListOf(84.88, 100.25, 999.99)

    (nonNulls as java.util.ArrayList).addAll(arrayOf("x", "y"))


    /**
     * 读写数组需要用MutableList<T>显式修饰
     */
    var stringList:MutableList<String> = ArrayList()
    stringList.add("zhangsan")
    stringList.add("lisi")

    var beanList: MutableList<MyBean> = ArrayList()
    var myBean = MyBean()
    myBean.name = "zhangsan"
    myBean.age = 27
    beanList.add(myBean)
}

Map

几种常用的map

fun map() {
    var map = mapOf("a" to 1, "b" to 2, "c" to 3)
    var value = map["b"]

    var states: MutableMap<String, String> =
            mutableMapOf(
                    "AL" to "Alabama",
                    "AK" to "Alaska",
                    "AZ" to "Arizona")

    val myBean: java.util.HashMap<Int, MyBean> = hashMapOf(
            1 to MyBean("ZhangSan", 12, false),
            2 to MyBean("LiSi", 13, true))

    val linkedHashMap: java.util.LinkedHashMap<String, String> =
            linkedMapOf("red" to "#FF0000", "black" to "#000000", "white" to "#FFFFFF")

    val sortedMap: java.util.SortedMap<Int, String> = sortedMapOf(4 to "d",
            1 to "a", 3 to "c", 2 to "b")
}

Set

Set是没有重复项的容器,可以用来去重

fun set(){
    //int
    val intSet: Set<Int> = setOf(1, 21, 21, 2, 6, 3, 2) //1,21,2,6,3
    //hash
    val hashSet: java.util.HashSet<MyBean> = hashSetOf(
            MyBean("Zhang San",14, false),
            MyBean("Zhang San",14, false))
    //sort
    val sortedIntegers: java.util.TreeSet<Int> = sortedSetOf(11, 0, 9, 11, 9, 8)
}
作者:lftaoyuan 发表于2017/8/30 19:05:59 原文链接
阅读:14 评论:0 查看评论

Viewing all articles
Browse latest Browse all 5930

Trending Articles