Search code examples
javaandroidcomparatorcomparable

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)"


Solution

  • You are not comparing Floats, you are comparing Results 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);
        }
    }