java.lang.ClassCastException:无法转换为 java.lang.Comparable

java.lang.ClassCastException: cannot be cast to java.lang.Comparable

在这种方法中,我想按升序对浮点值进行排序,为此我编写了 class 置信度比较器(参见下面的源代码)

public final PriorityQueue<Result> getResults(){
    PriorityQueue outputQueue = new PriorityQueue(createOutputQueue());

    for (int i =0; i<results.length+1;i++){
        Result res = new Result(labels.get(i), results[i]);
        outputQueue.add(res);
    }
    return outputQueue;

}
private final PriorityQueue<Result> createOutputQueue(){
    Comparator<Float> comparator = new ConfidenceComparator();
    return new PriorityQueue(labels.size(),comparator);
}

置信比较器:

public class ConfidenceComparator implements Comparator<Float> {     

public int compare(Float x, Float y) {                            

   return x.compareTo(y); }

抛出异常:

"java.lang.ClassCastException: jannik.weber.com.brueckenklassifikator.classifier.Result cannot be cast to java.lang.Comparable" 

getResults()方法中的outputQueue增加了两个置信度后。

我还尝试在结果 class 中实现可比接口,因为它按自然顺序对值进行排序:

public class Result implements Comparable{
private String result;
private float confidence;

@Override
public int compareTo(Object o) {
    Result other = (Result) o;
    return this.confidence.compareTo(other.confidence);
}

但是显示错误 "Cannot resolve method compareTo(float)"

您不是在比较 Float,而是在比较 Result 和其中的浮点值。 确实应该 Comparable<Result>

然后试试这个,因为 confidence 不是一个对象,在你的 compareTo:

return Float.compare(this.confidence, other.confidence);

完整代码:

public class Result implements Comparable<Result> {
    private String result;
    private float confidence;

    @Override
    public int compareTo(Result other) {
        return Float.compare(this.confidence, other.confidence);
    }
}