Android Kotlin学习(四)- 集合遍历

Android Kotlin学习(四)- 集合遍历

    • List
    • Set
    • Map

介绍下Kotlin常用的集合的创建和遍历

List

arrayListOf创建可变集合,可以提供索引访问元素,

var list1 = arrayListOf(User("test1","123456","123456"),User("test2","123456","123456"));
    list1.add(User("test3","123456","123456"));
    for (user in list1){
        Log.i(TAG,"list1 = "+user.name);
    }
    for (i in 0 until list1.size){
        Log.i(TAG,"list1 == "+list1[i].name);
    }

打印

23056-23056/com.kotlin.demo I/MainActivity: list1 = test1
23056-23056/com.kotlin.demo I/MainActivity: list1 = test2
23056-23056/com.kotlin.demo I/MainActivity: list1 = test3
23056-23056/com.kotlin.demo I/MainActivity: list1 == test1
23056-23056/com.kotlin.demo I/MainActivity: list1 == test2
23056-23056/com.kotlin.demo I/MainActivity: list1 == test3

Set

var set1 = hashSetOf(User("test1","123456","123456"),User("test2","123456","123456"));
    set1.add(User("test3","123456","123456"));
    for (user in set1){
        Log.i(TAG,"set1 = "+user.name);
    }

打印

23056-23056/com.kotlin.demo I/MainActivity: set1 = test1
23056-23056/com.kotlin.demo I/MainActivity: set1 = test3
23056-23056/com.kotlin.demo I/MainActivity: set1 = test2

Map

键值对存储

  var map1 = hashMapOf("test1" to User("test1","123456","123456"),
        "test2" to User("test2","123456","123456"));
    map1.put("test3",User("test3","123456","123456"))
    for ((name,user) in map1){
        Log.i(TAG,"map1 = "+name+";"+user.name);
    }

打印

23056-23056/com.kotlin.demo I/MainActivity: map1 = test1;test1
23056-23056/com.kotlin.demo I/MainActivity: map1 = test2;test2
23056-23056/com.kotlin.demo I/MainActivity: map1 = test3;test3

你可能感兴趣的:(android,kotlin,学习)