实现Comparable的Java警告

我正在尝试在自定义对象的ArrayList上使用Collections.sort,但我收到警告,我无法弄清楚为什么

Warning: Type safety: Unchecked invocation sort(ArrayList) of the generic method sort(List) of type Collections 

使用此代码:

 ArrayList charOccurrences = new ArrayList(); ... 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是

 public class CharProfile implements Comparable{ @Override public int compareTo(CharProfile cp) { ... } } 

您正在使用generics,因此请将传递给方法CharProfile而不是Object

我还建议重新排列比较,如果概率是双倍的话。

 @Override public int compareTo(CharProfile o) { if (this.probability < o.getProbability()) { return -1; } else if (this.probability > o.getProbability()) { return 1; } else { return 0; } } 

注意到已经回答了,但无论如何这里是我的输入:)

 import java.util.ArrayList; import java.util.List; import java.util.Collections; public class CharProfile implements Comparable { public void doStuff(){ List charOccurrences = new ArrayList(); Collections.sort(charOccurrences); } @Override public int compareTo(CharProfile o) { return -1; } }