2012-10-29 44 views
8

我试图使用Collections.sort自定义对象的ArrayList的,但我得到一个警告,我想不通为什么Java的警告与实施可比

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; 
     } 
} 
} 
+0

什么是“其他”的“的compareTo()”方法开始在做什么? –

回答

21

可比较应与类型实现,此处类型为<CharProfile>

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

您使用仿制药,所以让你传递给方法类型而不是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; 
     } 
} 
-2

注意到,已经回答了,但这里是我输入反正:)

import java.util.ArrayList; 
import java.util.List; 
import java.util.Collections; 

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

是你写的有效的compareTo()吗? – divine