简体   繁体   English

为什么`test2()`方法编译成功,但是`test1()`没有编译?

[英]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.

相关问题 为什么test1()的运行速度比test2()快? - Why does test1() run much faster than test2()? Test1和Test2在同一软件包中,为什么我需要导入test2? 如果我不使用import,Inn inn1 = test2.new Inn(4),它将出错 - Test1 & Test2 in the same package, so why do I need import test2? if I don't use import, Inn inn1 = test2.new Inn(4), It will go wrong 仅在@ Test1通过时运行@ Test2 - Only run @Test2 when @Test1 passes Test2阵列初始化错误 - Test2 Array Initialization Error 名称冲突:类型为test2的方法add(Object)具有与HashSet类型的add(E)相同的擦除 <E> 但不会覆盖它 - Name clash: The method add(Object) of type test2 has the same erasure as add(E) of type HashSet<E> but does not override it 为什么在空引用上调用方法成功编译? - Why does invoking a method on a null reference compile successfully? 为什么“mvn test”会编译测试类但只运行其中的一部分? - Why does “mvn test” compile test classes but only runs some of it? 为什么此代码涉及“?” 超级T”编译成功吗? - Why does this code involving “? super T” compile successfully? 如何测试该方法不会引发异常? - How to test that the method doesn't throw an exception? 测试Mockito Junit方法不起作用 - Test mockito junit method doesn't work
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM