tags:

views:

121

answers:

3

Hi, I was trying to write a generic class, that could operate on any simple type (int, float, etc.). I wanted to avoid repeating the same function several times, with changing the type of parameter. But since the generic parameter is a reference, I cannot do any calculations on variables of its type, like in C++ templates.

So is there any simple way in Java to use arithmetic operators on generic type variables? I know that I could use class-checking, and casting, but I think it would be much more code, and impact on performance. However I only recently started to write in Java, so I may be wrong.

A: 

Java 1.5 should handle this for you through autoboxing

Moose Morals
I think the question is about generics. If you define a method `T foo<T extends Number>( T value )` you cannot do any arithmetic. Autoboxing doesn't help here.
tangens
+2  A: 

One solution could be to use a template method:

T foo<T extends Number>( T value )

and do the calculations by using value.intValue(), value.longValue(), value.doubleValue().

tangens
+3  A: 

There's no way to do this how you would in C++, sorry. Generics in Java work quite differently to C++ templates. In Java, only one version of the generic code is ever generated, and it has to be suitable for all type arguments. Because all the primitives have different representations in byte code, they can't share the same generic code. This is why only reference types are valid type arguments in Java.

I think the closest you could get would be to use the Number class. Autoboxing will automatically convert any primitive numeric value into a subclass of Number. E.g:

class Foo<T extends Number> {
  public void operate(T number) {
    double value = number.doubleValue();
    // do something with the double
  }
}
Foo<Integer> intFoo = new Foo<Integer>();
intFoo.operate(666);
intFoo.operate(666.0); // fails to compile

But the type parameter isn't really buying you much. And if you want the operate method to return a value of type T, you have to resort to runtime checks, which kind of defeats the purpose.

A possibly interesting side note: Scala 2.8 will support an annotation @specialize that basically tells the compiler "handle the type arguments the C++ way", and generates a different version of the code for each different type argument representation.

Lachlan