为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

至尊宝的传说 2019-04-24 18:15:45
我正在阅读以下内容, 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请问有人告诉我发生了什么以及为什么会出错?
查看完整描述

1 回答

?
当年话下

TA贡献1890条经验 获得超9个赞

从编译器的角度来看:

T不是一个StringInteger.parseInt(...)希望传入。

并且Integer.parseInt(...)会返回一个int不是的X


查看完整回答
反对 回复 2019-05-15
  • 1 回答
  • 0 关注
  • 402 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号