我正在尝试对自定义对象的 ArrayList 使用 Collections.sort,但我收到了警告,而且我无法弄清楚原因
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应该以类型安全的方式实现,这里是<CharProfile>
.
public class CharProfile implements Comparable<CharProfile>{
@Override
public int compareTo(CharProfile cp) {
...
}
}
关于实现 Comparable 时的 Java 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13122718/