2011-11-20 2 views
1

내가 새로운 정수를 돌려 줄에 found java.lang.Integer Required Tin the Generic sparse matrix addition question자바 제네릭 또한

class Matrix<T extends Number> 
{ 
    private T add(T left, T right) 
    { 
    if (left instanceof Integer) 
    { 
    return new Integer(((Integer)left).intValue() + ((Integer)right).intValue()); 
    } 
} 

컴파일러 오류를 언급했다. 나는 T가 Number를 상속 받았기 때문에 내가 무엇을 놓쳤는 지 모르겠다. Integer는 Number의 하위 클래스이다.

+0

'Cat'은'Animal'을 확장하고,'Dog'는'Animal'의 서브 클래스입니다. 그렇다고해서 Cat이 예상되는 곳에 Dog를 반환 할 수있는 것은 아닙니다. –

+0

@OliCharlesworth T에 캐스팅을 시도했지만 도움이되지 않았다. –

+0

@ NuclearGhost : 어떤 오류가 있었습니까? – SLaks

답변

4

TDouble과 같은 다른 클래스 일 수 있기 때문에 컴파일러에서 허용하지 않습니다.
instanceof 수표에서 Integer이지만 컴파일러는 알지 못합니다.

0

"T가 Number를 확장하고 Integer가 Number의 하위 클래스이므로 누락 된 것이 확실하지 않습니다."

이 문장은 거짓입니다.

public class B extends A { 
} 

public class C extends A { 
} 

는 그 B가 C. 그래서 같은 것을 쓰기에 캐스트 할 수 있음을 의미하지 않습니다 :

public <T extends A> T method(T arg) { 
    return (B)arg; 
} 

을하고 B b = (B)method(C);으로 호출하는 것은 분명히 잘못된 것입니다 일반적으로 당신이있는 경우.

+0

아 맞습니다. 똑같은 것을 확장한다고해서 그것들이 똑같지는 않습니다. –

2

Java의 유형 시스템은 단순히이를 표현할 수 없습니다. 여기에 해결 방법이 있습니다.

관심있는 수치 연산을 제공하는 인터페이스 Numeric를 만들고 관심있는 데이터 형식의 구현을 작성합니다.

interface Numeric<N> { 
    public N add(N n1, N n2); 
    public N subtract(N n1, N n2); 
    // etc. 
} 

class IntNumeric extends Numeric<Integer> { 
    public static final Numeric<Integer> 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. 
} 

을 그리고이 구현을 허용하도록 Matrix 클래스 생성자를 다시 작성.

class Matrix<N> { 
    private final Numeric<N> num; 
    private final List<List<N>> contents; 

    public Matrix(Numeric<N> num) { 
    this.num = num; 
    this.contents = /* Initialization code */; 
    } 

    public Matrix<N> add(Matrix<N> that) { 
    Matrix<N> out = new Matrix<N>(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<Integer> m = new Matrix<Integer>(IntNumeric.INSTANCE); 

희망이 있습니다.

-2

패키지 제네릭;

public class Box<T> { 

     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<Integer> integerBox = new Box<Integer>(); 
     Box<Float> floatBox = new Box<Float>(); 

     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()); 
     } 
    } 
+0

당신은 그것이 무엇을하는지, 어떻게 해결할 수 있는지/설명을하지 않고 코드를 게시해서는 안됩니다. 그런데, 목적에 부합하기 때문에'@SuppressWarnings ("unchecked")'을 코드에 추가하면 안됩니다. 그리고 다른 것은 : 당신의 코드는 Exception에 대해 매우 취약합니다. – Tom