比较两个通用数字的值 [英] Comparing the values of two generic Numbers
问题描述
我想比较变量,这两个类型都是 T extends Number
。现在我想知道两个变量中的哪一个大于另一个或相等。不幸的是,我不知道确切的类型,我只知道它是 java.lang.Number
的子类型。我怎么做到这一点?
编辑:我尝试了另一种解决方法,使用 TreeSet
s ,它实际上与自然顺序一起工作(当然,它的工作原理是, Comparable
的所有子类) )。因此我会失去重复的价值。当使用 List
s时, Collection.sort()
不会接受我的列表,因为绑定不匹配。非常不满意。
一个工作(但很脆弱)的解决方案就像这样:
class NumberComparator实现了Comparator< Number> {
public int compare(Number a,Number b){
return new BigDecimal(a.toString())。compareTo(new BigDecimal(b.toString()));
}
}
尽管如此,因为它依赖于 toString
返回可由 BigDecimal
解析的值(其中标准Java Number
类做的,但是 Number
合约不需要)。
编辑,七年后:正如在评论中指出的那样,(至少?)三个特殊情况 toString
可以产生你需要的东西认为:
-
Infinity
,除了它本身以外,是相等的 -
-Infinity
,它比所有东西都要小,除了与它相同的本身 -
NaN
,因为所有与NaN
比较的结果都是false
,包括检查与自己的平等。
I want to compare to variables, both of type T extends Number
. Now I want to know which of the two variables is greater than the other or equal. Unfortunately I don't know the exact type yet, I only know that it will be a subtype of java.lang.Number
. How can I do that?
EDIT: I tried another workaround using TreeSet
s, which actually worked with natural ordering (of course it works, all subclasses of Number
implement Comparable
except for AtomicInteger and AtomicLong). Thus I'll lose duplicate values. When using List
s, Collection.sort()
will not accept my list due to bound mismatchs. Very unsatisfactory.
A working (but brittle) solution is something like this:
class NumberComparator implements Comparator<Number> {
public int compare(Number a, Number b){
return new BigDecimal(a.toString()).compareTo(new BigDecimal(b.toString()));
}
}
It's still not great, though, since it counts on toString
returning a value parsable by BigDecimal
(which the standard Java Number
classes do, but which the Number
contract doesn't demand).
Edit, seven years later: As pointed out in the comments, there are (at least?) three special cases toString
can produce that you need to take into regard:
Infinity
, which is greater than everything, except itself to which it is equal-Infinity
, which is less than everything, except itself to which it is equalNaN
, which is extremely hairy/impossible to compare since all comparisons withNaN
result infalse
, including checking equality with itself.
这篇关于比较两个通用数字的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!