kotlin中,如何来比较对象相等?我们都知道比较相等,一般有2种概念:
值相等
引用地址相等
==比较基本数据类型相等,比如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(())
println(())
// == equals , 比较的都是字符串的值。
println(s1 == s2)
println((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