java generic addition

前端 未结 4 1130
-上瘾入骨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:17

    Java's type system is simply not capable of expressing this. Here is a work around.

    Create an interface Numeric that provides the numeric operations you are interested in, and write its implementations for the data types you are interested in.

    interface Numeric {
      public N add(N n1, N n2);
      public N subtract(N n1, N n2);
      // etc.
    }
    
    class IntNumeric extends Numeric {
      public static final Numeric INSTANCE = new IntNumeric();
    
      private IntNumeric() {
      }
    
      public Integer add(Integer a, Integer b) {
        return a + b;  
      }
    
      public Integer subtract(Integer a, Integer b) {
        return a - b;  
      }
    
      // etc.
    }
    

    And rewrite your Matrix class constructor to accept this implementation.

    class Matrix {
      private final Numeric num;
      private final List> contents;
    
      public Matrix(Numeric num) {
        this.num = num;
        this.contents = /* Initialization code */;
      }
    
      public Matrix add(Matrix that) {
        Matrix out = new Matrix(num);
        for( ... ) {
          for( ... ) {
            out.contents.get(i).set(j,
              num.add(
                this.contents.get(i).get(j),
                that.contents.get(i).get(j),
              )
            );
          }
        }
        return out;
      }
    }
    
    // Use site
    Matrix m = new Matrix(IntNumeric.INSTANCE);
    

    Hope that helps.

提交回复
热议问题