Java减去通用值运算符减未定义

Waq*_*tho 5 java generics

我试图从提供的数组(2D数组)中减去该值。我想使用泛型来做。任何人都可以帮助解决我的代码的问题。我的意思是我需要上课吗?我遇到了错误(运算符-未为参数类型T,T定义)

提前致谢。

//this method Subtracts Value from the given Matrix for all the rows but for given columns 
private <T> void subtractValueFromColumns(T[][] matrix,
        ArrayList<Integer> columnsIndex, T value) {

    for(int i = 0; i < matrix.length; i++){
        for(int j = 0; j < columnsIndex.size(); j++){
            matrix[i][j] = matrix[i][j] - value;
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

Epi*_*rce 1

您需要定义可用于该给定类型的操作和方法。

public interface ArithmeticOps<T extends ArithmeticOps<T>>
{
    T add(T other);
    T subtract(T other);
    T divide(T other);
    T multiply(T other);
}

private <T extends ArithmeticOps<T>> void subtractValueFromColumns(T[][] matrix,
        List<Integer> columnsIndex, T value) {
    for(int i = 0; i < matrix.length; i++){
        for(int j = 0; j < columnsIndex.size(); j++){
            matrix[i][j] = matrix[i][j].subtract(value);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它类似于 LibGDX 的矢量运算方式。

https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/math/Vector.java

 public interface Vector<T extends Vector<T>> {
    /** Scales this vector by a scalar
     * @param scalar The scalar
     * @return This vector for chaining */
    T scl (float scalar);

    T add (T v);
}
Run Code Online (Sandbox Code Playgroud)

https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/math/Vector2.java

public class Vector2 implements Serializable, Vector<Vector2> {
    @Override
    public Vector2 scl (float x, float y) {
        this.x *= x;
        this.y *= y;
        return this;
    }

    @Override
    public Vector2 add (Vector2 v) {
        x += v.x;
        y += v.y;
        return this;
    }
}
Run Code Online (Sandbox Code Playgroud)