你可以用一些有趣的泛型编写一个 Vector 类
public static class Vector<V extends Vector<V>>{
protected double[] components;
public final int dimensions;
private Class<V> klass;
protected Vector(int d, Class<V> klass) {
this.klass = klass;
this.components = new double[d];
}
public double get(int x) { return components[x] }
protected void set(int x, double d) { components[x] = d }
public V clone() {
try {
V c = klass.newInstance();
c.components = this.components.clone();
return c;
}
catch(InstantiationException e1) {}
catch(IllegalAccessException e2) {}
return null;
}
public V add(V that) {
V sum = this.clone();
for(int i = 0; i < dimensions; i++)
sum.components[i] += that.components[i];
return sum;
}
}
然后推导出每个案例:
public static class Vector2D extends Vector<Vector2D>{
public Vector2D() {
super(2, Vector2D.class);
}
public Vector2D(double x, double y) {
this();
set(0, x);
set(1, y);
}
}
public static class Vector3D extends Vector<Vector3D>{
public Vector3D() {
super(3, Vector3D.class);
}
public Vector3D(double x, double y, double z) {
this();
set(0, x);
set(1, y);
set(2, z);
}
}
public static class Vector4D extends Vector<Vector4D>{
public Vector4D() {
super(4, Vector4D.class);
}
public Vector4D(double w, double x, double y, double z) {
this();
set(0, w);
set(1, x);
set(2, y);
set(3, z);
}
}
毕竟,有一些特殊情况——例如,叉积只存在于 3 维和 7 维中。每个都有一个实现可以解决这个问题。