Reputation: 666
I am reading the following, https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html in particular the part "Type Inference and Generic Constructors of Generic and Non-Generic Classes".
I have tried to run the following:
public class MyClass < X > {
X myObject;
<T> MyClass(T t, X x) {
myObject = x;
System.out.println("t is " + x.getClass().getName());
System.out.println("x is " + t.getClass().getName());
System.out.println("myObject is " + myObject.getClass().getName());
System.out.println("t value is " + t);
System.out.println("x value is " + x);
System.out.println("myObject value is " + myObject);
myObject = new Integer(t); // 1
}
public static void main(String[] args) {
String myString = "1";
MyClass<Integer> myObject = new MyClass<>(myString, new Integer(myString));
}
}
but I get the following compilation error:
$javac -Xdiags:verbose MyClass.java
MyClass.java:15: error: no suitable constructor found for Integer(T)
myObject = new Integer(t); // 1
^
constructor Integer.Integer(int) is not applicable
(argument mismatch; T cannot be converted to int)
constructor Integer.Integer(String) is not applicable
(argument mismatch; T cannot be converted to String)
where T,X are type-variables:
T extends Object declared in constructor <T>MyClass(T,X)
X extends Object declared in class MyClass
1 error
If I comment //1 there is no error and the output is
t is java.lang.Integer
x is java.lang.String
myObject is java.lang.Integer
t value is 1
x value is 1
myObject value is 1
Can somebody tell me please what's happening and why the error?
Upvotes: 0
Views: 99
Reputation: 57164
From the compiler's perspective:
T
is not a String
, which Integer.parseInt(...)
expects to be passed in.
And Integer.parseInt(...)
would return an int
which is not an X
.
Upvotes: 2