Collections.emptyList() returns a List<Object>?

前端 未结 4 752
轮回少年
轮回少年 2020-12-02 04:23

I\'m having some trouble navigating Java\'s rule for inferring generic type parameters. Consider the following class, which has an optional list parameter:

im         


        
4条回答
  •  既然无缘
    2020-12-02 04:47

    the emptyList method has this signature:

    public static final  List emptyList()
    

    That before the word List means that it infers the value of the generic parameter T from the type of variable the result is assigned to. So in this case:

    List stringList = Collections.emptyList();
    

    The return value is then referenced explicitly by a variable of type List, so the compiler can figure it out. In this case:

    setList(Collections.emptyList());
    

    There's no explicit return variable for the compiler to use to figure out the generic type, so it defaults to Object.

提交回复
热议问题