使用不同的T类调用print(List <T> a,T b)时发生错误 [英] Errors occur when calling print(List<T> a, T b) with different T class
问题描述
public static< T>< p> void print(T a,T b){
System.out.println(a);
System.out.println(b);
}
public static void main(String [] args){
print(new ArrayList< String>(),1);
}
其中没有问题。
然而,当我将 print
方法更改为以下内容时,它会给我编译错误。
public static< T> void print(List< T> a,T b){
System.out.println(a);
System.out.println(b);
错误:
<$ GenericTest.java:9:错误:类GenericTest中的方法打印不能应用于给定的类型;
print(new ArrayList< String>(),1);
$
required:List< T>,T
found:ArrayList< String>,int
reason:没有类型变量(s)T的实例存在,参数类型int符合形式参数类型T
其中T是类型变量:
T extends在方法< T> print(List< T> T)中声明的对象
1错误
任何人都可以帮我理解错误吗?
首先您应该了解的是,使用以下方法签名
公共静态< T> void print(T a,T b)
T
必须是相同的类型,也就是说 a
和 b
将会有相同的传染类型。
为什么它对新的ArrayList< String>()
和 1
?因为这两个参数实际上可以表示为 Serializable
,它是最接近的常见超类型 ArrayList
和整数
:
-
ArrayList
实现Serializable
接口。 / li>
-
1
可以装入Integer
,它也是Serializable $ c
所以在这种情况下,编译器会推断出
T
作为Serializable
。
在第二种情况下,
public static< T> void print(List
a,T b)
没有常见的超类型
T
对List< String>
和整数
都是有效的。确实,String
和Integer
都是Serializable
,但由于泛型不是多态,它不起作用。I am trying to learn Java Generics, and found the following code.
public static <T> void print(T a, T b){ System.out.println(a); System.out.println(b); } public static void main(String[] args){ print(new ArrayList<String>(), 1); }
Which works with no problem.
However when I change
print
method to the following, it gives me compiling errors.public static <T> void print(List<T> a, T b){ System.out.println(a); System.out.println(b); }
Error:
GenericTest.java:9: error: method print in class GenericTest cannot be applied to given types; print(new ArrayList<String>(), 1); ^ required: List<T>,T found: ArrayList<String>,int reason: no instance(s) of type variable(s) T exist so that argument type int conforms to formal parameter type T where T is a type-variable: T extends Object declared in method <T>print(List<T>,T) 1 error
Can anyone help me understand the errors?
解决方案The first thing you should understand is that, with the following method signature
public static <T> void print(T a, T b)
Both
T
must be the same type, that is to say botha
andb
will have the same infered type.So why does it work for
new ArrayList<String>()
and1
? Because both parameters can actually be represented asSerializable
, which is the nearest common super type ofArrayList
andInteger
:ArrayList
implements theSerializable
interface.1
can be boxed into anInteger
, which is alsoSerializable
.
So in this case, the compiler will infer
T
asSerializable
.
In the second case, with the signature
public static <T> void print(List<T> a, T b)
There is no common super type
T
that would be valid for bothList<String>
andInteger
. It is true that bothString
andInteger
areSerializable
, but since generics aren't polymorphic, it doesn't work.这篇关于使用不同的T类调用print(List <T> a,T b)时发生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!