I'm trying to create a custom class the creates matrices and, among other things, performs operations that add up all of the cells or multiply them all. However, I want to use generics so the matrices can be any type of number: float, double, int, etc. I have thus set up the class like this:
public class Matrix<num>
Upon initialization, the instantiation of this class creates a matrix based on user supplied data, stored in the instance's .matrix variable. Now, in the code where I want to add up all of the cells, I do something like this:
public num addMatrices(num[][] toAdd){
num result;
if (toAdd.length != this.rows && toAdd[0].length != this.columns){
System.out.println("Matrix mismatch. Try Again.");
return toAdd[0][0];
}
for (int i=0; i<rows; i++)
for (int j=0; j<rows; j++){
result = this.matrix[i][j] + toAdd[i][j];
}
}
I'm running into multiple problems, however. First of all, I can't initialize result to zero, which makes it hard to perform += operations. Secondly, when I try to add the cells of the two matrices, the compiler tells me that the + operator is undefined for the type num.
I thought the whole point of generics was to have a catchall type so I could do things like use floats in one case and ints in another, but if I need to specify the type for operators like +, I'm not sure where the advantage comes in...
You can't perform operations like +
and -
on Objects (some special cases excluded). Generics are all about Object types, so your use case for them isn't ideal.
That said, you can turn your declaration into something like public class Matrix<num extends Number>
, which will let you pass in Integer
, Double
, BigInteger
, etc. then you can then use something like num.longValue()
or num.doubleValue()
to get the long or double representations of your numbers. You would then need to return a double
or long
or whatever from your method instead of your generic type, though.
the other option would be to create a custom container class that has methods for add, subtract, etc. Then your class declaration can be public class Matrix<num extends Custom>
. You would have to figure out how to account for adding longs to doubles and returning the Custom type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With