I want to create a method that compares a number but can have an input that is any of the subclasses of Number.
I have looked at doing this in the following manner...
public static <T extends Number> void evaluate(T inputNumber) {
if (inputNumber >= x) {
...
}
}
I need to get the actual primative before I can perform the comparison, the Number class has methods to retrieve this for each primative but I want a clean way of selecting the correct one.
Is this possible?
Cheers
In Java: Generics are object only. There are no mathematical operators for objects.
The generic class works with multiple data types. A normal class works with only one kind of data type.
A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.
The Number
API doesn't offer a clean way to get the value; you have have to use instanceof
.
One solution is to "fold" the values into two types: long
and double
. That way, you can use this code:
if( inputNumber instanceof Float || inputNumber instanceof Double ) {
double val = inputNumber.doubleValue();
...
} else {
long val = inputNumber.longValue();
...
}
Note that this only works for the standard number types but Number
is also implemented by a lot of other types (AtomicInteger
, BigDecimal
).
If you want to support all types, a trick is to use BigDecimal
:
BigDecimal value = new BigDecimal( inputNumber.toString() );
That should always work and give you the most exact result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With