我遇到了以下情况,想知道我实现它的方式在可重用性和速度方面是否很好,我也有兴趣拥有一个实际的可编译解决方案,因为下面的解决方案无法编译(我希望有人找到了罪魁祸首,并对此有一个简单而优雅的想法)。
有两个 Java 类“Vec3F”和“Vec3”实现了浮点和 double 类型的基本 vector 数学。两者都实现如下接口(interface):
public final class Vec3 implements Vec<Vec3> {
//..
public double distance(Vec3 other) { /*..*/ }
}
public interface Vec<V> {
double distance(V other);
}
我这样做是为了能够让一些算法适用于两种类型的 vector 实现,但问题来了:
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”,但这是我想避免的。我希望有一个工具箱类可以根据接口(interface)中声明的方法执行一些元算法。 我还想避免更改例如的方法实现distance(Vec3 other) 传递接口(interface)(因为它直接使用例如 other.x*other.x 以避免调用任何 getter)。
我很高兴对此有一些想法,希望问题足够清楚和具体,在此先感谢!
最佳答案
您可能希望将 Vec 接口(interface)定义为:
public interface Vec<V extends Vec<V>>
这可能很难看,因为乍一看像是非法的前向引用,但它是完全有效且正常的(事实上在 java.lang.Enum 中使用)。
每当你有一个Vec<T>
例如,你必须传递 T
, 不是 Vec<T>
, 至 distance
方法。所以你需要像这样定义你的 getAllDistances 方法:
public static <T extends Vec<T>> double getAllDistances(List<T> points) {
T prevPoint = points.get(0);
T point;
关于java - 用于实现通用接口(interface)的 2 个以上类的高级 Java 习惯用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32488318/