Java template classes using generator or similar?

Posted by Hugh Perkins on Stack Overflow See other posts from Stack Overflow or by Hugh Perkins
Published on 2012-10-13T03:23:17Z Indexed on 2012/10/13 9:37 UTC
Read the original article Hit count: 185

Is there some library or generator that I can use to generate multiple templated java classes from a single template?

Obviously Java does have a generics implementation itself, but since it uses type-erasure, there are lots of situations where it is less than adequate.

For example, if I want to make a self-growing array like this:

 class EasyArray {
      T[] backingarray;
 }

(where T is a primitive type), then this isn't possible.

This is true for anything which needs an array, for example high-performance templated matrix and vector classes.

It should probably be possible to write a code generator which takes a templated class and generates multiple instantiations, for different types, eg for 'double' and 'float' and 'int' and 'String'. Is there something that already exists that does this?

Edit: note that using an array of Object is not what I'm looking for, since it's no longer an array of primitives. An array of primitives is very fast, and uses only as much space a sizeof(primitive) * length-of-array. An array of object is an array of pointers/references, that points to Double objects, or similar, which could be scattered all over the place in memory, require garbage collection, allocation, and imply a double-indirection for access.

Edit2: good god, voted down for asking for something that probably doesn't currently exist, but is technically possible and feasible? Does that mean that people looking for ways to improve things have already left the java community?

Edit3:

Here is code to show the difference in performance between primitive and boxed arrays:

int N = 10*1000*1000;
double[]primArray = new double[N];
for( int i = 0; i < N; i++ ) {
    primArray[i] = 123.0;
}
Object[] objArray = new Double[N];
for( int i = 0; i < N; i++ ) {
    objArray[i] = 123.0;
}
tic();
primArray = new double[N];
for( int i = 0; i < N; i++ ) {
    primArray[i] = 123.0;
}
toc();
tic();
objArray = new Double[N];
for( int i = 0; i < N; i++ ) {
    objArray[i] = 123.0;
}
toc();

Results:

double[] array: 148 ms
Double[] array: 4614 ms

Not even close!

© Stack Overflow or respective owner

Related posts about java

Related posts about templates