如果java抽象类“Number"的任何对象等于零 [英] If any object of the java abstract class "Number" is equal to zero

查看:28
本文介绍了如果java抽象类“Number"的任何对象等于零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个通用函数,它接受任何类型的 Number 并在该数字等于 0 时有条件地执行某些操作.我希望任何人都能够将扩展 数字(BigDecimal、BigInteger、Byte、Double、Float、Integer、Long 或 Short)

I'm trying to make a generic function that takes any type of Number and conditionally does something if that number is equal to zero. I want anyone to be able to pass it any of the classes that extend Number (BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, or Short)

到目前为止,我已经尝试使用 instanceof 来找出数字的类型,然后将其与等效类型进行比较

So far, I've attempted to use instanceof to find out what type the number is, then compare it to an equivalent type

public static boolean isZero(Number number) {
    if (number instanceof BigDecimal) {
        return BigDecimal.ZERO.equals(number);
    } else if (number instanceof BigInteger) {
        return BigInteger.ZERO.equals(number);
    } else if (number instanceof Byte) {
        return new Byte((byte) 0).equals(number);
    } else if (number instanceof Double) {
        return new Double(0).equals(number);
    } else if (number instanceof Float) {
        return new Float(0).equals(number);
    } else if (number instanceof Integer) {
        return new Integer(0).equals(number);
    } else if (number instanceof Long) {
        return new Long(0).equals(number);
    } else if (number instanceof Short) {
        return new Short((short) 0).equals(number);
    }
    return false;
}

这行得通,但它很长而且很麻烦.有什么办法可以简化这个吗?

This works, but it is quite long and cumbersome. Is there any way to simplify this?

推荐答案

不幸的是,这在一般情况下是不可能做到的;零"甚至不能保证可以用一般的 Number 表示(因为你可以设计一个PositiveInteger"类,它只表示正数并且仍然遵循 Number> 类规范).

Unfortunately, this is not possible to do in a general way; "Zero" isn't even guaranteed to be representable by a general Number (because you could e.g. design a "PositiveInteger" class that only represents positive numbers and still adheres to the Number class spec).

尝试将值转换为任何其他类可能会导致截断或舍入,这会使您的测试无效,因此不幸的是,使用 Number 类本身的任何方法都可能会产生错误的结果.

Attempting to convert the value to any other class may cause truncation or rounding, which would invalidate your test, so unfortunately using any method of the Number class itself will probably produce incorrect results.

这篇关于如果java抽象类“Number"的任何对象等于零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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