java generic addition

前端 未结 4 1078
-上瘾入骨i
-上瘾入骨i 2021-01-25 01:23

I\'m attempting implement the add method mentioned in the Generic sparse matrix addition question

class Matrix
{
  private T add(T left,          


        
4条回答
  •  滥情空心
    2021-01-25 02:19

    "I'm not sure what I'm missing since T extends Number and Integer is a subclass of Number."

    This statement is false. In general if you have:

     public class B extends A {
     }
    
     public class C extends A {
     }
    

    it does not mean that B can be cast to C. So writing something like:

     public  T method(T arg) {
         return (B)arg;
     }
    

    and you calling it with B b = (B)method(C); is obviously wrong.

提交回复
热议问题