使用比较器帮助比较浮点型成员变量 [英] Help comparing float member variables using Comparators
本文介绍了使用比较器帮助比较浮点型成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以很好地比较字符串,但是想知道如何对浮点数进行排名?
I am able to compare Strings fine, but would like to know how I can rank floating point numbers?
getChange()返回一个字符串.我希望能够对降序进行排序.我该怎么办?
getChange() returns a String. I want to be able to sort descending. How can I do this?
更新:
package org.stocktwits.helper;
import java.util.Comparator;
import org.stocktwits.model.Quote;
public class ChangeComparator implements Comparator<Quote>
{
public int compare(Quote o1, Quote o2) {
float change1 = Float.valueOf(o1.getChange());
float change2 = Float.valueOf(o2.getChange());
if (change1 < change2) return -1;
if (change1 == change2) return 0; // Fails on NaN however, not sure what you want
if (change2 > change2) return 1;
}
}
我收到了编译时错误:
This method must return a result of type int ChangeComparator.java
推荐答案
Read the javadoc of Comparator#compare()
method.
比较其两个参数的顺序. 当第一个参数小于,等于或大于第二个参数时,返回负整数,零或正整数.
因此,基本上:
float change1 = o1.getChange();
float change2 = o2.getChange();
if (change1 < change2) return -1;
if (change1 > change2) return 1;
return 0;
或者,如果您喜欢条件运算符:
Or if you like conditional operators:
return o1.getChange() < o2.getChange() ? -1
: o1.getChange() > o2.getChange() ? 1
: 0;
但是,您需要考虑 Float.NaN
.我不确定您要如何订购它们.第一的?最后的?同样吗?
You however need to take account with Float.NaN
. I am not sure how you'd like to have them ordered. First? Last? Equally?
这篇关于使用比较器帮助比较浮点型成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文