kotlin中,如何来比较对象相等?

2021-02-2421:51:34编程语言入门到精通Comments1,756 views字数 1655阅读模式

kotlin中,如何来比较对象相等?我们都知道比较相等,一般有2种概念:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/20981.html

值相等
引用地址相等

==比较基本数据类型相等,比如Int,Boole,String,其中String可以支持 == 或者equals()来比较相等文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/20981.html

var  a=1
var b=1
a==b
// 字符串比较.
private fun test1() {
    val s1 = "Doug"
    // 使用这种方式创建就是为了创建两个地址不同的字符串。
    val s2 = String(charArrayOf('D', 'o', 'u', 'g'))
    println(s1)
    println(s2)
    // 如果两个字符串的值相同那么hashCode也相等.说
    println(())
    println(())
    // == <==> equals , 比较的都是字符串的值。
    println(s1 == s2)
    println((s2))
    // === 比较两个对象的引用是否相同。
    println(s1 === s2)
}

=== 三个等号,比较的是值和引用地址相等,一般用户比较对象是否相等,重写 equals,equals方法是基类Any里面的,Any是所有类的爸爸文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/20981.html

package kotlin

/**
 * The root of the Kotlin class hierarchy. Every Kotlin class has [Any] as a superclass.
 * Kotlin类层级中的根节点, kotlin中的任何类都是Any的子类.
 */
public open class Any {
    /**
     * 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.
     * 
     * 备注 : 在kotlin中如果两边的参数都不为null,  `==`就会被翻译成equals()方法,
     */
    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.
     * 
     * 同一个对象多次调用hashCode返回的值应该是相同的, 如果两个对象使用equals方法得到true那么这两个对象
     * 的hashCode应该是相同的.
     * 
     */
    public open fun hashCode(): Int

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

对象比较相等,重写equals和hashCode方法文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/20981.html

class Person(val name:String) {
    /**
     * equals 通用写法.
     */
    override fun equals(other: Any?): Boolean {
        return when (other) {
            !is Person -> false
            else -> this === other || this.name == other.name
        }
    }
}

比较对象相等文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/20981.html

val a = Person("Alex", 20)
val b = Person("Alex", 20)
println(a == b)
println(a === b)

打印结果:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/20981.html

true
false
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/20981.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/20981.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定