java generic addition

前端 未结 4 1113
-上瘾入骨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条回答
  •  萌比男神i
    2021-01-25 02:19

    package generics;

    public class Box {
    
          public T j,k;
          int l;
          float f;
    
          @SuppressWarnings("unchecked")
        public void add(T j,T k) {
            this.j = j;
            this.k=k;
    
            if(j.toString().contains("."))
            {
                  this.f=Float.parseFloat(j.toString())+Float.parseFloat(k.toString());
    
    
            } else{
            this.l=Integer.parseInt(j.toString())+Integer.parseInt(k.toString());
            }
          }
    
          public int getInt() {
            return l;
          }
    
          public float getFloat() {
                return f;
              }
    
          public static void main(String[] args) {
             Box integerBox = new Box();
             Box floatBox = new Box();
    
             integerBox.add(new Integer(10),new Integer(20));
             floatBox.add(new Float(2.2),new Float(3.3));
    
             System.out.printf("Integer Value :%d\n\n", integerBox.getInt());
             System.out.printf("float Value :%f\n", floatBox.getFloat());
          }
        }
    

提交回复
热议问题