gpt4 book ai didi

java - 泛型和非泛型类的类型推断和泛型构造函数

转载 作者:行者123 更新时间:2023-12-02 01:30:46 28 4
gpt4 key购买 nike

我正在阅读以下内容, 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 MyClass
1 error

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

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

有人可以告诉我发生了什么以及为什么会出现错误吗?

最佳答案

从编译器的角度来看:

T 不是 Integer.parseInt(...) 期望传入的 String

并且 Integer.parseInt(...) 将返回一个 int,它不是 X

关于java - 泛型和非泛型类的类型推断和泛型构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56101034/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com