[英]Why does `test2()` method compile successfully, but `test1()` doesn't?
Please, consider the Test
Java class below. 请考虑下面的
Test
Java类。
Why does test2()
method compile successfully, but test1()
doesn't? 为什么
test2()
方法编译成功,而test1()
没有编译?
import java.util.Arrays;
import java.util.List;
public class Test {
public <N extends Number> List<N> test1(){
//compile error: Type mismatch: cannot convert from List<Integer> to List<N>
return Arrays.asList(1,2,3);
}
public List<? extends Number> test2(){
//no compile error
return Arrays.asList(1,2,3);
}
}
It will become clearer if you write the code that calls these methods. 如果您编写调用这些方法的代码,它将变得更加清晰。
For example: 例如:
public static void main (String args) {
Test obj = new Test();
List<Double> list1 = obj.test1 ();
List<? extends Number> list2 = obj.test2 ();
}
As you can see, the output of test1()
can be assigned to a List<Double>
, which means it cannot return a List<Integer>
. 如您所见,可以将
test1()
的输出分配给List<Double>
,这意味着它不能返回List<Integer>
。
On the other hand, the output of test2()
can be assigned only to a List<? extends Number>
另一方面,只能将
test2()
的输出分配给List<? extends Number>
List<? extends Number>
or a List<? extends Object>
List<? extends Number>
或List<? extends Object>
List<? extends Object>
or a List<?>
, and a List<Integer>
can be assigned to all three. List<? extends Object>
或List<?>
,并且可以将List<Integer>
分配给所有这三个对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.