0

I've got a question referring to this post: Java generics to enforce return type of abstract method and Björn's answer in particular: https://stackoverflow.com/a/1627646

Isn't it possible to use primitive data types for the data type specifier? Specifically, I have the problem that I have an abstract class "Matrix" and two sub-classes which inherit from "Matrix". One is "ComplexMatrix" which basically is a Matrix with complex entries. Therefore, I created a class "Complex". The other is a "normal" double matrix.

public abstract class Matrix<T> {
    public abstract T getValue(int r, int c);
}

public class ComplexMatrix extends Matrix<Complex> {
    public Complex getValue(int r, int c){
        return null;
    }
}

public class DoubleMatrix extends Matrix<double> {
    public double getValue(int r, int c){
        return double.NaN;
    }
}

The first one, ComplexMatrix, works. The second one does't. It says for < double>: "unexpected type required reference found double".

If I use the Wrapper class Double

public class DoubleMatrix extends Matrix<Double> {
    public double getValue(int r, int c){
        return Double.NaN;
    }
}

the error message says, that "return type double is not compatible with Double" where T is a type variable.

Can someone please tell me why this isn't working? Why does it work with "< String>"?

Thanks.

Community
  • 1
  • 1
raedma
  • 293
  • 1
  • 12
  • 5
    You cannot use primitive types with generics. You've changed the type argument in `Matrix<...>` but not in the return type. – Sotirios Delimanolis Feb 24 '14 at 13:45
  • 2
    `public double getValue(int r, int c){` => `public Double getValue(int r, int c){` in your last attempt – assylias Feb 24 '14 at 13:46
  • You cannot use primitives in generics. http://stackoverflow.com/questions/2721546/why-dont-java-generics-support-primitive-types – m-szalik Feb 24 '14 at 13:46
  • So based on "So, anything that is used as generics has to be convertable to Object (in this example get(0) returns an Object), and the primitive types aren't." So they can't be used in generics." from jw23's link, the thing I try to achieve cannot be done? – raedma Feb 24 '14 at 13:54

1 Answers1

0

Java Compiler replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. As in your example double is a primitive type. So your getting that error.

Check this link http://docs.oracle.com/javase/tutorial/java/generics/erasure.html

cerberus
  • 531
  • 4
  • 14