美文网首页
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之集合

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