I'm trying to create some Java classes, that should work with either float or double numbers (for simulation purposes I am required to support both). The classes need to do some basic arithmetic and also require use of trigonometric functions (sin, cos, atan2).
I tried to do a generic approach. As Java does not allow primitive types in generics and MyClass<T extends Number>
does indeed allow Double and Float, but makes basic arithmetic impossible, I build a wrapper class around Double and Float. But this approach fails, as soon as I need to instantiate a value in one of the generic classes.
Is there any clean way to support both float and double, without duplicating all the code for each type?
You have to add the numbers as the same type, so you could do x. intValue() + y. intValue(); .
Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes the code stable by detecting the bugs at compile time. Before generics, we can store any type of objects in the collection, i.e., non-generic.
Maybe this is what you are looking for?
class MyClass<T extends Number> {
T add(T t1, T t2) {
if (t1 instanceof Double) {
return (T) Double.valueOf((t1.doubleValue() + t2.doubleValue()));
} else if (t1 instanceof Float) {
return (T) Float.valueOf(((t1.floatValue() + t2.floatValue())));
} else if (t1 instanceof Integer) {
return (T) Integer.valueOf(((t1.intValue() + t2.intValue())));
}
// you can add all types or throw an exception
throw new IllegalArgumentException();
}
public static void main(String[] args) {
MyClass<Double> mc = new MyClass<Double>();
mc.add(1.0, 1.1);
}
}
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