gpt4 book ai didi

java - 错误: compareTo(Object) in Car cannot implement compareTo(T) in Comparable

转载 作者:行者123 更新时间:2023-11-30 04:27:12 29 4
gpt4 key购买 nike

public int compareTo(Object another) throws CustomMadeException
{
if(this.getClass() != another.getClass() )
{
throw new CustomMadeException();
}

Car other = (Car) another;


return this.getBrand().compareTo(other.getBrand());


}

我不明白我的代码到底出了什么问题。为什么它不能在Comparable中实现T?我是否必须将compareTo的参数更改为T?但不应该是Object吗?据我所知,compare接口(interface)中compareTo的实现是空白的。

最佳答案

执行此操作的规范方法如下:

public class Car implements Comparable<Car> {

...

public int compareTo(Car other)
{
return this.getBrand().compareTo(other.getBrand());
}
}

请注意,您的 compareTo() 的实现不能抛出任何检查异常,因为 Comparable<T>.compareTo() 不允许任何异常的throws规范。

关于java - 错误: compareTo(Object) in Car cannot implement compareTo(T) in Comparable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15591557/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com