我遇到了以下情况,我想知道我实现它的方式是否在可重用性和速度方面是好的,我也有兴趣有一个实际的可编译解决方案,因为下面的那个没有编译(我希望有人找到了罪魁祸首,对此有一个简单而优雅的想法。
有两个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类可以根据接口中声明的方法做一些元算法。 我还想避免改变例如的方法实现。传递接口的距离(Vec3其他)(因为它直接使用例如other.x * other.x来避免调用任何getter)。
对于这方面的一些想法,我很高兴,并希望这个问题清晰而具体,提前感谢!