Extended Java idiom for classes 2+ implementing a common interface

I came across the following situation, and I’m interested in the way I implemented it, it’s good in terms of reuse and speed, I would also be interested to have a ready-made solution, because the one below does not compile (I hope someone finds a criminal and has a simple and elegant idea about this).

There are two Java classes “Vec3F” and “Vec3” that implement basic vector math for floating point and double types. Both interfaces implement below:

public final class Vec3 implements Vec<Vec3> {
//..
    public double distance(Vec3 other) { /*..*/ }
}

public interface Vec<V> {

    double distance(V other);   
}    

I did this in order to have some algorithms for working with both types of vector implementations, and here the problem arises:

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, - ).

, , !

+4
2

, Vec :

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;
+4

, :

public static <T extends Vec<T>> double getAllDistances(List<T> points) {
    T prevPoint = points.get(0);
    T point;
    double sum = 0.0;
    int len = points.size();
    for (int i=1;i<len; i++) {
        point = points.get(i);

        sum+=point.distance(prevPoint);
        prevPoint = point;
    }
    return sum;
}

, < Vec < T → T. , .

+4

Source: https://habr.com/ru/post/1606651/


All Articles