简体   繁体   English

在矩阵加法/乘法中使用泛型

[英]Using Generics in Matrix Addition/Multiplication

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: 但是,我想使用泛型,因此矩阵可以是任何类型的数字:float,double,int等。因此我设置了这样的类:

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. 初始化时,此类的实例化会根据用户提供的数据创建一个矩阵,该矩阵存储在实例的.matrix变量中。 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. 其次,当我尝试添加两个矩阵的单元格时,编译器告诉我+类型为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... 我认为泛型的全部要点是有一个类型,所以我可以做一些事情,比如在一个案例中使用浮点数,在另一个案例中使用ints,但是如果我需要为+等运算符指定类型,我不确定它的优势在哪里进来...

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. 也就是说,您可以将声明转换为public class Matrix<num extends Number> ,这将允许您传入IntegerDoubleBigInteger等,然后您可以使用num.longValue()num.doubleValue()获得数字的长或双表示。 You would then need to return a double or long or whatever from your method instead of your generic type, though. 然而,您需要返回一个doublelong或者您的方法而不是您的泛型类型。

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> . 另一种选择是创建一个自定义容器类,它具有add,subtract等方法。然后你的类声明可以是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. 您必须弄清楚如何将long添加到双精度并返回Custom类型。

The problem is that you num can be anything. 问题是你的num可以是任何东西。 So, for example, what would it need to do if you created a Matrix<Object> ? 那么,例如,如果您创建了Matrix<Object> ,它需要做什么?

You could try to make your number extend from Number , but even then you won't be able to use + because java don't know what to cast this generic to. 您可以尝试使您的数字从Number扩展,但即便如此,您将无法使用+因为java不知道将此泛型转换为什么。

You could create a method similar to your Matrix with generic that does that. 您可以创建一个类似于您的Matrix的方法,使用泛型。 Something like 就像是

public static <NUM extends Number> NUM add(NUM[][] matrixA, NUM[][] matrixB, NumFunction<NUM> function) {
    // all equals to your add method, but the result you get with
    result = function.apply(this.matrix[i][j], toAdd[i][j]);
}

public interface NumFunction<NUM extends Number> {
    NUM apply(NUM operA, NUM operB);
}

You will need to duplicate NumFunction to every type of Number , or create one generic that checks what type of Number is with "instanceof". 您需要将NumFunction复制到每种类型的Number ,或者创建一个通用NumFunction来检查Number与“instanceof”的类型。 It's not very pretty :P 它不是很漂亮:P

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM