麻烦帮忙解答一下
来源:4-3 案例:对商品价格进行降序排序
慕沐1462760
2020-08-05 15:31:25
老师我使用上一节的Cat类来改写的,如下,将Object改为Cat会报错,是怎么回事,像下面这么写就没事,
@Override
public int compareTo(Object arg0) {
int age1=this.getMonth();
int age2=((Cat)arg0).getMonth();
return age1-age2;
}
然后在CatTest类中写为Collections.sort(catList);会有下面的预警信息,怎么回事
Type safety: Unchecked invocation sort(List<Cat>) of the generic method sort(List<T>) of type Collections
1回答
好帮手慕小尤
2020-08-05
同学你好,1. 在实现compareTo()方法的接口实现类中,声明class MyClass implements Comparable后面没有跟对象类型,导致实现compareTo(Object)方法的参数只能为默认的Object类(正确的参数应该使用我自己定义的类),所以导致后续调用Collections.sort()时对于List对象的类型是否匹配产生警告。
2. 同学可尝试修改为在class MyClass implements Comparable<MyClass>加入我自己定义的类型,
3. 如果还存在问题,则建议同学反馈全部代码,便于老师定位问题。
祝学习愉快!
相似问题