Kotlin集合框架(对比Java)

2020-09-05  本文已影响0人  demoyuan
通过上图可以看出:对比Java,Kotlin增加了"不可变"集合框架的接口

集合框架的创建

Java

//List的创建
List<String> stringList = new ArrayList<>();

List<Integer> intList = new ArrayList<Integer>(Arrays.asList(1, 2, 3));
//Map的创建
Map<Integer,Object> iMap = new HashMap<>();

Map<String, Object> sMap = new HashMap<>();
sMap.put("name", "jack");
sMap.put("age", 12);

Kotlin

//List的创建
val stringList1: List<String> = ArrayList<String>()//不可变的List
val stringList2: MutableList<String> = ArrayList<String>()//可变的List

val intList1: List<Int> = listOf(1, 2, 3)//不可变的List
val intList2: MutableList<Int> = mutableListOf(1, 2, 3)//可变的List
//Map的创建
val iMap1: Map<Int, Any> = HashMap<Int, Any>()//不可变的Map集合
val iMap2: MutableMap<Int, Any> = HashMap<Int, Any>()//可变的Map集合

val sMap1: Map<String, Any> = mapOf("name" to "jack", "age" to 12)//不可变的Map集合
val sMap2: MutableMap<String, Any> = mutableMapOf("name" to "jack", "age" to 12)//可变的Map集合

集合框架的读写

Java

for (int i = 0; i <= 10; i++) {
    stringList.add("item:" + i);
}
for (int i = 0; i <= 10; i++) {
    stringList.remove("item:" + i);
}

stringList.set(3,"hello world");
System.out.println(stringList.get(3));

Map<String, Integer> map = new HashMap<>();
map.put("hello", 10);
System.out.println(map.get("hello"));

Kotlin

for (i in 0..10) {
    stringList2 += "item:$i"//等价于 stringList2.add("item:$i")
}
for (i in 0..10) {
    stringList2 -= "item:$i"//等价于 stringList2.remove("item:$i")
}

stringList2[3] = "hello world"
println(stringList2[3])

val map = HashMap<String, Int>()
map["hello"] = 10;//等价于map.put("hello", 10)
println(map["hello"])//等价于map.get("hello")

Kotlin中特有的对象Pair

val pair = "hello" to "kotlin"//等价于 Pair("hello", "kotlin")
val firstValue = pair.first//获取第一个值  "hello"
val secondValue = pair.second// 获取第二个值 "kotlin"
val (x, y) = pair//解构表达式的写法

前面在讲解Kotlin中Map创建的时候提到过Pair,就是键值对。其实Pair就是一个类,它的构造方法有两个参数,并且有两个属性firstsecond可以获得这两个值

Kotlin中特有的对象Triple

val triple = Triple("hello", 10, 15.5)
val firstValue = triple.first//获取第一个值 "hello"
val secondValue = triple.second//获取第二个值 10
val thirdValue = triple.third//获取第三个值 15.5
val (x, y, z) = triple//解构

Triple的创建方式就只有1种了,就是通过构造创建对象的方式。包含3个元素。

最后,集合框架的循环迭代和包含关系等都和数组一样,可以参考我之前写的Kotlin数组那篇讲解https://www.jianshu.com/p/726d09c7da5e

上一篇 下一篇

猜你喜欢

热点阅读