Kotlin/Java重写equals后==表现(2)
如果不重写默认的equals方法,即使用Object默认的equals()方法,而Object默认的equals方法,其实比较两个对象的地址:
fun main(args: Array<String>) {
val u1 = User("zhang", 1)
val u2 = User("phil", 2)
println("$u1 ${u1.hashCode()}")
println("$u2 ${u2.hashCode()}")
println("${u1 == u2} ${u1.equals(u2)}")
}
class User {
private var name: String? = null
private var id: Int = 0
constructor(name: String, id: Int) {
this.name = name
this.id = id
}
}
User@1ddc4ec2 500977346
User@133314b 20132171
false false
如果重写了equals方法:
fun main(args: Array<String>) {
val u1 = User("zhang", 2024)
val u2 = User("phil", 2024)
println("$u1 ${u1.hashCode()}")
println("$u2 ${u2.hashCode()}")
println("${u1 == u2} ${u1.equals(u2)}")
}
class User {
private var name: String? = null
private var id: Int = 0
constructor(name: String, id: Int) {
this.name = name
this.id = id
}
override fun equals(other: Any?): Boolean {
val u = other as User
return u.id == this.id
}
}
User@1ddc4ec2 500977346
User@133314b 20132171
true true
因为重写了equals方法,那么== 或者 equals 比较两个对象是否相同,则调用重写后的equals方法,而equals方法只是比较两个对象的id,而id都是2024,所以均返回true。
https://zhangphil.blog.csdn.net/article/details/136516174https://zhangphil.blog.csdn.net/article/details/136516174