kotlin 对象比较相等

在kotlin中,如何来比较对象相等?我们都知道比较相等,一般有2种概念:

值相等
引用地址相等

Kotlin中的相等运算符有三个 == , ===, equals():

==比较基本数据类型相等,比如Int,Boole,String,其中String可以支持 == 或者equals()来比较相等

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(s1.hashCode())
    println(s2.hashCode())
    // == <==> equals , 比较的都是字符串的值。
    println(s1 == s2)
    println(s1.equals(s2))
    // === 比较两个对象的引用是否相同。
    println(s1 === s2)
}

=== 三个等号,比较的是值和引用地址相等,一般用户比较对象是否相等,重写 equals,equals方法是基类Any里面的,Any是所有类的爸爸

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方法

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
        }
    }
}

比较对象相等

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

打印结果:

true
false
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值