实现 Comparable 时的 Java 警告

标签 java

我正在尝试对自定义对象的 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/

相关文章:

java - 保护使用以共享包中的变量

java - 将字符串转换为 xml 元素 java

java - Java中的 "this"如何转义构造函数?

java - IntelliJ 重构为内联冗余数据类

java - 如何检查 Java 中是否使用了 Enum

java 。帮助找出为什么我的代码不起作用

java - 安卓 : ViewPager OnClickListener NullPointerException

java - 监控数据库 : MySQL

java - 发送和接收用户定义对象的套接字程序不起作用

java - Android Studio - fragment 按钮 Action