Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Generics in Matrix Addition/Multiplication

Tags:

java

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

like image 822
user1427661 Avatar asked Nov 12 '22 12:11

user1427661


1 Answers

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.

like image 160
Peter Elliott Avatar answered Nov 15 '22 05:11

Peter Elliott