【发布时间】:2015-12-05 22:33:50
【问题描述】:
我遇到了以下情况,想知道我实现它的方式在可重用性和速度方面是否良好,我也有兴趣拥有一个实际可编译的解决方案,因为下面的解决方案无法编译(我希望有人找到了罪魁祸首,并对此有一个简单而优雅的想法)。
有两个 Java 类“Vec3F”和“Vec3”实现了浮点和双精度类型的基本向量数学。两者都实现了如下接口:
public final class Vec3 implements Vec<Vec3> {
//..
public double distance(Vec3 other) { /*..*/ }
}
public interface Vec<V> {
double distance(V other);
}
我这样做是为了让一些算法适用于这两种类型的向量实现,问题就来了:
public class Toolbox {
public static <T> double getAllDistances(List<Vec<T>> points) {
Vec<T> prevPoint = points.get(0);
Vec<T> point;
double sum = 0.0;
int len = points.size();
for (int i=1;i<len; i++) {
point = points.get(i);
//-> this doesn't compile:
//The method distance(T) in the type Vec<T> is not applicable for the arguments (Vec<T>)
sum+=point.distance(prevPoint);
prevPoint = point;
}
return sum;
}
}
我知道我可以实现两次“getAllDistances”,但这是我想要避免的。我希望有一个 Toolbox 类,它可以根据接口中声明的方法执行一些元算法。 我也想避免改变例如的方法实现distance(Vec3 other) 让接口通过(因为它直接使用例如 other.x*other.x 以避免调用任何 getter)。
我很高兴对此有一些想法,并希望问题足够清晰和具体,在此先感谢!
【问题讨论】:
-
这不是CRTP的工作吗?
-
您需要澄清类型代表什么。 “点”真的是 T 的向量还是 T 对象? Vec和Vec3是什么关系?距离(V other)中的“其他”是一个点吗? Vec3F 在哪里?
-
Vec3F 实现了与 Vec3 相同的接口,但使用 float x,y,z;而不是双 x,y,z;在它的所有方法中。其他在 Vec3 中实现时为“Vec3”类型,在浮点 Vec3F 类实现距离时为“Vec3F”类型。
标签: java algorithm generics meta typesafe