简体   繁体   中英

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

In this method I want to sort Float values in ascending order, for this I wrote the class Confidence Comparator (see sourcecode below)

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);
}

ConfidenceComparator:

public class ConfidenceComparator implements Comparator<Float> {     

public int compare(Float x, Float y) {                            

   return x.compareTo(y); }

This throws the exception:

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

after two confidences have been added to the outputQueue in the getResults() method.

I also tried implementing the comparable Interface in the Results class because it's sorting the values in their natural order:

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);
}

But it shows the error "Cannot resolve method compareTo(float)"

You are not comparing Float s, you are comparing Result s with a float value inside them. So should be Comparable<Result> indeed.

Then try this instead, as confidence is not an object, in your compareTo:

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

With the complete code:

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM