简体   繁体   中英

Why does `test2()` method compile successfully, but `test1()` doesn't?

Please, consider the Test Java class below.

Why does test2() method compile successfully, but test1() doesn't?

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> .

On the other hand, the output of test2() can be assigned only to a List<? extends Number> List<? extends Number> or a List<? extends Object> List<? extends Object> or a List<?> , and a List<Integer> can be assigned to all three.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM