You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kotlin自定义Dog类中基于体重实现比较运算符?

实现基于体重的Dog类compareTo方法

要实现基于体重的比较,直接利用weight属性本身的compareTo方法即可——因为你的泛型T已经限定为Comparable<T>,所以weight具备比较能力。

修改后的完整类代码如下:

class Dog<T: Comparable<T>>(private val name: T, private val weight: T): Comparable<Dog<T>> {
    override fun compareTo(other: Dog<T>): Int {
        // 基于体重比较两个Dog对象
        return weight.compareTo(other.weight)
    }
 
    override fun equals(other: Any?): Boolean {
        return (other is Dog<*>) && (other.weight == weight)
    }
}

验证运行效果

执行你提供的测试代码:

fun main() {
    val dog1 = Dog("Dog1", 10)
    val dog2 = Dog("Dog2", 11)
 
    println(dog1 > dog2) // 输出 false(10 < 11)
    println(dog1 <= dog2) // 输出 true(10 <= 11)
}

额外说明

你的equals方法已经基于weight判断对象相等,当前compareTo的实现完全符合Comparable接口的契约:当compareTo返回0时,equals必定返回true,保证了比较逻辑的一致性。

内容的提问来源于stack exchange,提问作者ntos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 20:31:01