Why is the difference in declaration of generic Lists?

前端 未结 2 541
被撕碎了的回忆
被撕碎了的回忆 2021-02-13 05:20

I want to decare two Lists: First is a list of Integers. I decare it as:

  List ints= Arrays.asList(1,2,3);

It works fine.

相关标签:
2条回答
  • 2021-02-13 06:04

    Look at this post on stackoverflow.

    15.12.2.7 Inferring Type Arguments Based on Actual Arguments

    A supertype constraint T :> X implies that the solution is one of supertypes of X. Given several such constraints on T, we can intersect the sets of supertypes implied by each of the constraints, since the type parameter must be a member of all of them. We can then choose the most specific type that is in the intersection

    The most restrictive type intersection between String,Double and Integer is both the interfaces Comparable and Serializable. So when you write

    Arrays.asList(1,2.13,"three"); 
    

    It infers T to be implements Comparable<?>, Serializable.Then it is as if you are doing

    List<Object> objs = new List<T extends Comparable<?>, Serializable>
    

    Obviously, this is not allowed.
    On the other hand, when you specify Object explicitly using

    Arrays.<Object>asList(1,2.13,"three");
    

    no inference is made

    0 讨论(0)
  • 2021-02-13 06:10

    Use this works perfect

    List<? extends Object> objs = Arrays.asList(10,20.32,"test");
    
    System.out.println(objs);
    

    Output: [10, 20.32, test]

    0 讨论(0)
提交回复
热议问题