If any object of the abstract class java "Number" is equal to zero

I am trying to create a universal function that accepts any type of Number and conditionally does something if this number is zero. I want someone to be able to pass him any of the classes that extend Number (BigDecimal, BigInteger, Byte, Double, Float, Integer, Long or Short)

So far I have been trying to use instanceof to find out what type this number is and then compare it with the 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; } 

It works, but it is rather long and bulky. Is there any way to simplify this?

+5
source share
1 answer

Unfortunately, this cannot be done in a general way; "Zero" is not even guaranteed to be represented by a common Number (because you could, for example, create a class "PositiveInteger" that represents only positive numbers and still adheres to the specification of the Number class).

Attempting to convert a value to any other class may result in truncation or rounding, which will invalidate your test, so unfortunately, using any method of the Number class is likely to produce incorrect results.

+6
source

Source: https://habr.com/ru/post/1200059/


All Articles