java - 如何在 Java 中初始化泛型变量?

标签 java generics initialization

我正在尝试编写一种方法,我需要在其中创建泛型 T 的临时变量 sum。但是,我收到错误消息“局部变量 sum 可能尚未初始化”。如何初始化泛型变量?我无法将它设置为 0 或 0.0,而且我无法在任何地方找到有关如何处理此问题的信息。这是我正在使用的代码部分:

public Matrix<T,A> multiply(Matrix<T,A> right) throws MatrixException
{
    Matrix<T,A> temp = new Matrix<T,A>(arithmetics, rowSize, columnSize);

    T sum, product;

    if (rowSize != right.columnSize)
        throw new MatrixException("Row size of first matrix must match column size " 
                + "of second matrix to multiply");

    setup(temp,rowSize,columnSize);

    for (int i = 0; i < rowSize; i++){
        for (int j = 0; j < right.columnSize; j++) {
            product = (arithmetics.multiply(matrix[i][j] , right.matrix[j][i]));
            sum = arithmetics.add(product, sum);
            temp.matrix[i][j] = sum;
        }
    }
    return temp;
}

我不确定这是否有助于澄清,但这是我的界面算术:

public interface Arithmetics<T> {

public T zero();
public T add( T a, T b );
public T subtract( T a, T b);
public T multiply (T a, T b);
public T parseString( String str );
public String toString( T a );

}

这是我的一个类,DoubleArithmetics,只是为了展示我是如何实现接口(interface)的:

public class DoubleArithmetics implements Arithmetics<Double> {

protected Double value;

public Double zero() 
{

    return new Double(0);
}

public Double add( Double a, Double b ) 
{

    return new Double(a.doubleValue()+b.doubleValue());
}

public Double subtract (Double a, Double b)
{
    return new Double(a.doubleValue()-b.doubleValue());
}

public Double multiply (Double a, Double b)
{
    return new Double(a.doubleValue()*b.doubleValue());
}

public Double parseString( String str )
{
    return Double.parseDouble(str);
}

public String toString( Double a )
{
    return a.toString();
}
}

最佳答案

只需使用界面上已有的zero 方法来初始化sum:

T sum = arithmetics.zero();

对于非零初始化,您还可以添加采用 longdouble 值并为它们返回 T 的方法:

public interface Arithmetics<T> {

    public T zero();
    public T create(long l);
    public T create(double d);
    public T add( T a, T b );
    public T subtract( T a, T b);
    public T multiply (T a, T b);
    public T parseString( String str );
    public String toString( T a );
}

然后实现它们:

public Double create(long l) {
    return new Double(l);
}

public Double create(double d) {
    return new Double(d);
}

最后,使用它们:

T one = arithmetics.create(1);

关于java - 如何在 Java 中初始化泛型变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17393526/

相关文章:

java - 泛型类型的injector.getInstance

c# - 允许在 typeof 表达式中引用未绑定(bind)类型的效用是什么?

我们可以在数组内联声明中分配更少的数组内容吗?

c# - 在C#中创建二维数组的数组

c++ - 有没有办法声明一个类,然后在 C++ 的函数中初始化它?

java - Saxonica 9.7.0.4 中的 com.saxonica.ptree.StylesheetPackager 发生了什么?

java - View 在被其他 View 覆盖时接收触摸事件

java - 格式化 LinkedHashMap

java - 有没有通用的 Maven 代码生成器?

.net - 通用约束是否应该优先于使用接口(interface)作为参数类型?