xan
xan

Reputation: 1053

How to do calculations on generalized types in Java?

I am implementing Polynomial class with generalized type of polynomial coefficients. I have this code:

public class Polynomial<T> {

private HashMap<Integer, T > polynomial;

public Polynomial(T coefficient, Integer index) {
    polynomial = new HashMap<Integer, T>();
    if (coefficient!=0) 
        polynomial.put(index, coefficient);
}

public void sum(Polynomial<T> w) {
    for (Map.Entry<Integer, T> e : w.polynomial.entrySet()) {
        T tmp = polynomial.get(e.getKey());
        if(tmp==null)
            polynomial.put(e.getKey(), e.getValue());
        else {
            polynomial.remove(e.getKey());
            if (tmp+e.getValue()!=0)
                polynomial.put(e.getKey(), tmp+e.getValue());
        }
    }
}

...

}

which for obvious reasons does not compile. Operators: ==, !=, +, - and * are not defined for generalized type T. From what I know in Java I can't override operators. How can I solve this problem?

Upvotes: 2

Views: 339

Answers (2)

Michał Kosmulski
Michał Kosmulski

Reputation: 10020

Since generics in Java work differently from those in C++, you can't use operators. You need to assure your type T implements some interface and use the interface's methods for the calculations. Suppose you used Number interface from standard library, which allows you to call doubleValue() on you object and calculate based on that, you could use a definition such as as private HashMap<Integer, T extends Number >, in which case you will be able to access Number's methods from T.

You could also make your own classes based on a custom interface with methods such as add(), mul() etc. Since these are method calls, you can't use native types here, so much of the performance is lost and there is less reason to write code such as in the example in Java than in C++. Some libraries, like Trove, go as far a actually using code generation in place of Java Generics to get a C++-like preprocessor-style behavior for a set of parametrized classes.

Upvotes: 2

Harry Cutts
Harry Cutts

Reputation: 1424

You can be a little more specific as to what types you accept when you declare your class. This means that you can specify that the type parameter must be a Number:

public class Polynomial<T extends Number>

You can then use the methods in the Number class (intValue(), doubleValue(), etc.) to turn it into a primitive, and do arithmetic on that. This isn't ideal, I know, but should work OK if you use doubleValue() and your numbers aren't too big.

Upvotes: 1

Related Questions