Generic static method constrains types too much

后端 未结 3 1674
北海茫月
北海茫月 2021-01-25 05:28

In this answer I attempted to create a static utility method to make a List into a Map:

public static  Map toMa         


        
3条回答
  •  清酒与你
    2021-01-25 06:10

    Your last line calls the method toMapBy in which the compiler infers the type Student for T. So it obviously returns a List.

    But generics aren't covariant!

    That means, you cannot assign a List to a variable of type List, because they are not in a subtype relationship.

    The solution is to use the subtype form:

    Map peopleById2 = toMapBy(students, Student::getId); // no compiler error
    

提交回复
热议问题