With the inclusion of generics it would be more obvious and much more clear to have a Vector class defined with generics like:
Vector
with n being the dimension and t the primitive or non-primitive type.
Thus we could avoid having a package with different classes that do almost exactly the same (Vector2f, Vector2d, Vector3f, Vector3d, …) poluting design.
The problem is that Java generics are only 1/2 generics so no primitive int types and no values passed has template parameters.
To try to solve this problem i come up with a scheme. A Vector class is defined like:
Vector(int dimension, Class clazz)
where clazz is a value like Float.TYPE that represents a primitive type.
The constructor body would be something like:
// A an array object representing a tuple
// Notice i don’t use the [] notation
Object tuple;
Vector(int dimension, Class clazz) {
// validate args
…
// create tuple
tuple = Array.newInstance(clazz, dimension);
}
Methods accessing the data structure use
reflection. For example:
void add(Vector v2) {
// check if this this is compatible with v2
Vector v1 = this;
int length = Array.getLength(v1.tuple);
switch (tuple.class.getComponentType()) {
case Float.TYPE:
for (int i=0; i < length; i++) {
float f1 = Array.getFloat(v1.tuple, i);
float f2 = Array.getFloat(v2.tuple, i);
Array.setFloat(v1.tuple, i, f1+f2);
}
break;
case … :
…
}
}
A more simple solution woud be to have:
FloatPoint(int dimension)
DoublePoint(int dimension)
this would avoid reflection but would still have to work with an array:
void add(DoubleVector v2) {
// check lengths
int length = tuple.length;
for (int i=0; i < length; i++)
this.tuple[i] += v2.tuple[i];
}
Of course that this would be the most efficient but at a great cost in terms of a clean design as you can see from the vecmath package clutered with similar classes:
void add(Vector2d v2) {
this.x += v2.x;
this.y += v2.y;
}
My question is how of a performance difference would we get from using reflection methods and from using the array method when compared to vecmath way ? Im asking this in case anyone has done a benchmark since im not very good at doing them.