美文网首页
Kotlin之集合

Kotlin之集合

作者: xu_pan | 来源:发表于2020-09-17 21:17 被阅读0次

list

//不可变集合
val intList: List<Int> = listOf(1, 2, 3, 4)
println(intList)
//输出[1, 2, 3, 4]


//可变集合
val intList2: MutableList<Int> = mutableListOf(1, 2, 3, 4)
intList2.add(5);
for (item in intList2.indices) {
    if (item == 3) {
        intList2.remove(item)
    }
}
println(intList2)
//输出[1, 2, 4, 5]

//集合倒序排列
intList2.sortDescending()
println(intList2)
//输出[5, 4, 2, 1]

//集合正序排列
intList2.sort()
println(intList2)
//输出[1, 2, 4, 5]


data class Student(var name: String, var score: Int)

val studentList: MutableList<Student> = mutableListOf()
studentList.add(Student("小a",100))
studentList.add(Student("小d",90))
studentList.add(Student("小e",95))
studentList.add(Student("小b",90))
//条件排序
studentList.sortBy { it.score }
println(studentList)
//输出[Student(name=小d, score=90), Student(name=小b, score=90), Student(name=小e, score=95), Student(name=小a, score=100)]
//多重条件排序
studentList.sortWith(compareBy({it.score},{it.name}))
println(studentList)
//输出[Student(name=小b, score=90), Student(name=小d, score=90), Student(name=小e, score=95), Student(name=小a, score=100)]

Set

val setStr:MutableSet<String> = mutableSetOf("h","e","l","l","o")//set会自动过滤重复元素
setStr.add("w")
setStr.remove("h")
println(setStr)
//输出 [e, l, o, w]

//set的加减操作
setStr += mutableSetOf<String>("w","o","r","l","d")
println(setStr)
//输出 [e, l, o, w, r, d]

setStr -= mutableSetOf<String>("w","d","A")
println(setStr)
//输出[e, l, o, r] 

Map

val mapString:MutableMap<Int,String> = mutableMapOf();

mapString[1] = "a"
mapString[2] = "b"
mapString.put(3,"c")//编译器建议使用mapString[3]= "c"的方式
println(mapString)
//输出{1=a, 2=b, 3=c}
println(mapString.keys)
//输出[1, 2, 3]
println(mapString.values)
//输出[a, b, c]
if(mapString.containsKey(2)){
    println("key-2 exist")
}
//输出 key-2 exist
if(mapString.containsValue("b")){
    println("Value-b exist");
}
//输出 Value-b exist


Q1:键值相同的两个map相等么

val mapString2:MutableMap<Int,String> = mutableMapOf();
mapString2[1] = "a"
mapString2[2] = "b"
mapString2.put(3,"c")
println("mapString = mapString2?${mapString == mapString2},${mapString.equals(mapString2)}")
//输出 mapString = mapString2?true,true

看看Java的比较结果为

HashMap<Integer,String> map1 = new HashMap<>();
map1.put(1,"a");

HashMap<Integer,String> map2 = new HashMap<>();
map2.put(1,"a");
System.out.println("map1=map2? "+(map1==map2)+" "+map1.equals(map2));
输出 map1=map2? false true

Java的结果是我们熟悉的,Java中“==”比较的实际上是“地址”,只有“地址”相同才可以认为相同。而equals比较的是值。但是Kotlin是为什么呢?
查看Kotlin中的“==”可以发现原来其重载了equals方法,所以不只是map,Kotlin中所有其它对象的==也等同于equals了

public open class Any {
    /**
     * Indicates whether some other object is "equal to" this one. Implementations must fulfil the following
     * requirements:
     *
     * * Reflexive: for any non-null reference value x, x.equals(x) should return true.
     * * Symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
     * * Transitive:  for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true
     * * Consistent:  for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
     *
     * Note that the `==` operator in Kotlin code is translated into a call to [equals] when objects on both sides of the
     * operator are not null.
     */
    public open operator fun equals(other: Any?): Boolean

    /**
     * Returns a hash code value for the object.  The general contract of hashCode is:
     *
     * * Whenever it is invoked on the same object more than once, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.
     * * If two objects are equal according to the equals() method, then calling the hashCode method on each of the two objects must produce the same integer result.
     */
    public open fun hashCode(): Int

    /**
     * Returns a string representation of the object.
     */
    public open fun toString(): String
}

debug “==” 查看到实际调用的方法为
Intrinsis.java中的

public static boolean areEqual(Object first, Object second) {
        return first == null ? second == null : first.equals(second);
}

相关文章

  • Kotlin学习之可变与不可变集合

    Kotlin学习之可变与不可变集合 一、可变集合与不可变集合有哪些? Kotlin集合框架在kotlin.coll...

  • Kotlin系列之四-集合

    Kotlin系列之四-集合 一.Kotlin中的集合 二.集合的操作 公共操作 这些⻚面中描述的操作将返回其结果,...

  • Kotlin之集合

    1、集合的创建与遍历 1.1、List集合的创建 在Java中常用的集合有ArrayList、LinkedList...

  • Kotlin之集合

    list Set Map Q1:键值相同的两个map相等么 看看Java的比较结果为 Java的结果是我们熟悉的,...

  • Kotlin常用Collection集合操作整理

    本篇记录了Kotlin常用集合的相关操作,用以熟练使用Kotlin里的相关集合。集合接口与相关函数位于kotlin...

  • Kotlin学习之List集合

    Kotlin学习之List集合 List是有顺序的数据结构,在Kotlin中提供了类似数组的访问方式: get()...

  • Kotlin详见集合与操作符

    [TOC] 前言 kotlin的集合分为不可变集合和可变集合 Kotlin 的 List 只提供只读...

  • Kotlin学习之常用高阶函数:filter

    Kotlin学习之常用高阶函数:filter Kotlin高阶函数一般是数组、集合、序列等数据结构的扩展函数,接收...

  • 第三篇:Kotlin之流程控制

    上篇:第二篇:Kotlin之运算符和表达式 下篇:第四篇:Kotlin之数组和集合 说起流程的话,相信学过ja...

  • 重拾Kotlin(11)-集合

    一、集合 1.1、只读集合与可变集合 Kotlin 的集合设计和 Java 不同的另一项特性是:Kotlin 把访...

网友评论

      本文标题:Kotlin之集合

      本文链接:https://www.haomeiwen.com/subject/bbpryktx.html