实现Comparable的Java警告 [英] Java warning with implementing Comparable
本文介绍了实现Comparable的Java警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在自定义对象的ArrayList上使用Collections.sort,但我收到警告,我无法弄清楚为什么
I'm trying to use Collections.sort on a ArrayList of custom objects, but I'm getting a warning and I can't figure out why
Warning: Type safety: Unchecked invocation
sort(ArrayList<CharProfile>) of the generic method sort(List<T>)
of type Collections
使用以下代码:
ArrayList<CharProfile> charOccurrences = new ArrayList<CharProfile>();
...
Collections.sort(charOccurrences);
这是我的方法:
public class CharProfile implements Comparable {
...
@Override
public int compareTo(Object o) {
if (this.probability == ((CharProfile)o).getProbability()) {
return 0;
}
else if (this.probability > ((CharProfile)o).getProbability()) {
return 1;
}
else {
return -1;
}
}
}
推荐答案
Comparable应该用type实现,这里Type是< CharProfile>
。
Comparable should be implemented with type, here Type is <CharProfile>
.
public class CharProfile implements Comparable<CharProfile>{
@Override
public int compareTo(CharProfile cp) {
...
}
}
这篇关于实现Comparable的Java警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文