Search code examples
javamathvectormath

One class for math vectors of arbitrary dimension


I want to write a class for mathematical Vectors (holding real numbers). I figured that Vector operations are pretty much the same regardeless of the dimension of the vector, so instead of writing classes like Vector2D, Vector3D, Vector4D, ... I just want to write a Vector class.

Now the problem is that I can't multiply a 2D vector with a 4D one, so I thought about a field dimension. But now I had to check it for every operation so I asked myself if I can do better than that. This is were generics came to my mind. But then again I have to do something like Vector<? extends Dimension>, where Dimension is simply a base class of Dimension.One, Dimension.Two and so on, which means, I have to write a Dimension class for every dimension I want to use vectos in.

So my question:

Is there a way of writing one class for vectors of arbitrary dimension without having to check the dimension at runtime?


Solution

  • If I understand your question correctly, then the answer is that you can't have both. Either you use the type system to ensure correct dimensionality, and then you end up with a proliferation of explicit types (generics won't help you), or you use state to track the dimensions and perform dynamic checks every time you perform an operation. Since the "dimension" of a vector is how many elements it holds, this will be represented somehow in the underlying data structure. For example if you use a list to store the values in the vector, the list knows how many elements it contains. So doing a simple runtime check is cheap and you can throw an exception when dimensions don't match. That solution is much more flexible and easy to program with than a type based solution.