[Proposal]

Sjoerd van Leent svanleent at gmail.com
Sun Jun 18 12:44:08 PDT 2006


Dave wrote:
> 
> public class Test
> {
>     public static void main(String args[])
>     {
>         Integer i = 100;
>         System.out.println(sqr(i));
>         int j = 1000;
>         System.out.println(sqr(j));
>     }
>     public static <T> T sqr(T x)
>     {
>         return x * x;
>     }
> }
> 
> However, I get this when I compile:
> 
> Test.java:10: operator * cannot be applied to T,T
>                 return x * x;
> 
> ?
> 
> Thanks,
> 
> - Dave


This is correct behaviour. You are now stating:

T must be of type Object. Type object doesn't have the * operator 
implemented. Even extending it from Number won't help, since the * 
operator doesn't work on class instances, only on primitives. To get it 
work you need quite a hack:

package generic.test;

import sun.reflect.generics.reflectiveObjects.NotImplementedException;

public class Test {
     public static void main(String args[]) {
         Integer i = 100;
         System.out.println(sqr(i));
         int j = 1000;
         System.out.println(sqr(j));
     }
     public static <T extends Number> T sqr(T x) {
     	if(x instanceof Integer) {
     		return (T)(Number)new Integer(x.intValue() * x.intValue());
     	} else if(x instanceof Byte) {
     		return (T)(Number)new Byte((byte)(x.byteValue() * x.byteValue()));
     	} else if(x instanceof Long) {
     		return (T)(Number)new Long(x.longValue() * x.longValue());
     	} else if(x instanceof Double) {
     		return (T)(Number)new Double(x.doubleValue() * x.doubleValue());
     	} else if(x instanceof Float) {
     		return (T)(Number)new Float(x.floatValue() * x.floatValue());
     	} else {
     		throw new NotImplementedException();
     	}
     }
}

Which is, if you ask me, not the best way of using Generics, well, I 
didn't invent them in Java, and it shows that it is really syntactic sugar.

Regards,
Sjoerd



More information about the Digitalmars-d mailing list