0

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

6
  • confidence is a primitive. Primitives don't have methods. Try Float.compare(this.confidence, other.confidence). Commented Jan 26, 2019 at 21:18
  • 2
    FYI: Do not use raw generics. Change implements Comparable to implements Comparable<Result> Commented Jan 26, 2019 at 21:19
  • Instead of this.confidence.compareTo(other.confidence) of course. Commented Jan 26, 2019 at 21:20
  • 2
    FYI: Do not use raw generics. Change all PriorityQueue to PriorityQueue<Result> Commented Jan 26, 2019 at 21:21
  • 1
    Whichever way you go: Do not use raw generics!! Commented Jan 26, 2019 at 21:22

1 Answer 1

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.