在这种方法中,我想按升序对Float值进行排序,为此,我编写了Confidence Comparator类(请参见下面的源代码)
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); }
这将引发异常:
"java.lang.ClassCastException: jannik.weber.com.brueckenklassifikator.classifier.Result cannot be cast to java.lang.Comparable"
在outputQueue
方法中将两个置信度添加到getResults()
之后。
我还尝试在Results类中实现可比较的Interface,因为它以自然顺序对值进行排序:
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)"
答案 0 :(得分:0)
您没有在比较Float
,而是在其中将Result
与一个浮点值进行比较。
确实应该Comparable<Result>
。
然后在您的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);
}
}