在 Kotlin 中,比较两个对象通常涉及两种方式:equals()
方法和 compareTo()
方法。
Comparable
接口,并重写 compareTo()
方法。Set
或 Map
)中,用于确定元素的唯一性。Comparable
接口的类中,可以直接使用 Collections.sort()
等方法进行排序。data class Person(val name: String, val age: Int)
fun main() {
val person1 = Person("Alice", 30)
val person2 = Person("Alice", 30)
val person3 = Person("Bob", 25)
println(person1 == person2) // true,因为 data class 自动生成了 equals() 和 hashCode()
println(person1 == person3) // false
}
data class Student(val name: String, val score: Int) : Comparable<Student> {
override fun compareTo(other: Student): Int {
return this.score.compareTo(other.score)
}
}
fun main() {
val students = listOf(
Student("Alice", 85),
Student("Bob", 92),
Student("Charlie", 78)
)
val sortedStudents = students.sorted()
println(sortedStudents) // 输出按分数排序的学生列表
}
equals()
和 hashCode()
时出现不一致。equals()
和 hashCode()
方法,导致逻辑上相等的对象具有不同的哈希码。equals()
和 hashCode()
方法,并保持它们的逻辑一致。class MyClass(val value: Int) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as MyClass
return value == other.value
}
override fun hashCode(): Int {
return value.hashCode()
}
}
通过这种方式,可以确保在使用集合类(如 HashSet
或 HashMap
)时,逻辑上相等的对象能够正确地被识别和处理。
领取专属 10元无门槛券
手把手带您无忧上云