Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics and the Number class

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

like image 763
Mr R Avatar asked Oct 13 '10 11:10

Mr R


People also ask

Is number a generic type in Java?

In Java: Generics are object only. There are no mathematical operators for objects.

What is difference between class and generic class?

The generic class works with multiple data types. A normal class works with only one kind of data type.

What are generic classes in Java?

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.


1 Answers

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.

like image 109
Aaron Digulla Avatar answered Sep 19 '22 14:09

Aaron Digulla