类型推断和泛型和非泛型类的通用构造函数

我正在阅读以下内容, https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html,特别是“通用和非通用类的类型推断和通用构造函数”部分。

我试图运行以下内容:

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));}}

但是我得到以下编译错误:

$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 MyClass1 error

如果我评论// 1没有错误,输出是

t is java.lang.Integerx is java.lang.StringmyObject is java.lang.Integert value is 1x value is 1myObject value is 1

请问有人告诉我发生了什么以及为什么会出错?


至尊宝的传说
浏览 403回答 1
1回答

当年话下

从编译器的角度来看:T不是一个String,Integer.parseInt(...)希望传入。并且Integer.parseInt(...)会返回一个int不是的X。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java