比较两个通用数字的值 [英] Comparing the values of two generic Numbers

查看:111
本文介绍了比较两个通用数字的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较变量,这两个类型都是 T extends Number 。现在我想知道两个变量中的哪一个大于另一个或相等。不幸的是,我不知道确切的类型,我只知道它是 java.lang.Number 的子类型。我怎么做到这一点?



编辑:我尝试了另一种解决方法,使用 TreeSet s ,它实际上与自然顺序一起工作(当然,它的工作原理是, Number 实现 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 可以产生你需要的东西认为:




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 TreeSets, 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 Lists, 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:

这篇关于比较两个通用数字的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆