Extending Generics to primitive types
843793Jan 31 2002 — edited Apr 6 2002The current generics proposal has section discussing why primitives were omitted. A variety of approaches are discussed, all of which have problems. However I think there is another approach which is not mentioned in that document. My proposal is effectively a hybrid between the homogeneous and heteorogenous approaches. For generic classes where the parameter types are all 'Objects' the treatment is exactly as in the current proposal.
A type parameter can allow either certain types of primitive or objects (constrained by class/interface), but never both. For a primitive type parameter the constraint can be 'number' (any of the numerical primitives), 'integer' (any integral primitive), or 'real' (float or double). This means that we know what operations are permitted on instances of the type. When an instance of a class with a primitive type parameter is required the ordinary byte code will have to be generated from the generic code. The code to perform this expansion can be written in Java and loaded dynamically when needed --- so the overhead is only paid if you use it. Memory constrained environments could have the code expanded ahead of time. Note that the expansion is only done with regard to the primitive parameters and not any object parameters.
So to take the java.util.Arrays class for example, the sort methods could be reduced to two:
a) for Object[] arguments
b) for number[] (primitive) arguments
This would expand to exactly the same code as we have know (assuming you used all the primitive variants). So the memory cost would be (size of generic byte code)+(size of expanded byte code for variants used)+(size of expansion code) - (size of original byte code for all variants).
A hook would be required in the JVM to invoke the expansion code when required but this would be trivial.
This is a very rough proposal just to indicate that a low cost solution is possible. It maintains the existing separation between primitive and object types, which will no doubt offend the purists. It would allow us to write basic methods for the primitive number types just once instead of 7 times as at present.
There are quite a few extra wrinkles required to make this a fully fledged proposal (e.g. a MIN_VALUE property on the parameterised type).
Comments?