How can I initialize a generic variable in Java?
generics, initialization, java
Solution
Just use the `zero` method that you already have on your interface to initialize `sum`:
T sum = arithmetics.zero();
For the non-zero initialization, you could also add methods that take `long` and `double` values and return the `T` for them:
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 );
}
And then implement them:
public Double create(long l) {
return new Double(l);
}
public Double create(double d) {
return new Double(d);
}
And finally, to use them:
T one = arithmetics.create(1);
Problem
I am trying to write a method in which I need to create a temp variable, sum, of generic type T. However, I'm getting the error "The local variable sum may not have been initialized". How can I initialize a generic variable? I can't set it to 0 or 0.0, and I can't find information anywhere on how to deal with this. Here is the portion of code that I'm working with: ``` 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; } ``` I'm not sure if this will help clarify, but here is my interface Arithmetics: ``` 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 ); } ``` And here is one of my classes, DoubleArithmetics, just to show how I'm implementing the 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(); } } ```