Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generic arithmetic

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?

like image 673
crater2150 Avatar asked Dec 17 '12 09:12

crater2150


People also ask

How do you add two generic values in Java?

You have to add the numbers as the same type, so you could do x. intValue() + y. intValue(); .

What is a generic method Java?

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.

What is Java Generics with examples?

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.

What is generic list in Java?

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.


1 Answers

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);
    }
}
like image 111
Evgeniy Dorofeev Avatar answered Sep 27 '22 23:09

Evgeniy Dorofeev