Java Generics: List, List<Object>, List<?>

后端 未结 12 1987
你的背包
你的背包 2020-11-22 17:08

Can someone explained, as detailed as possible, the differences between the following types?

List
List
List


Let me m

12条回答
  •  暖寄归人
    2020-11-22 18:02

    The shortest possible explanation is: The second item is a list that can hold any type, and you can add objects to it:

    List
    
    
    

    The first item you list is treated as essentially equivalent to this, except you will get compiler warnings because it is a "raw type".

    List
    

    The third is a list that can hold any type, but you cannot add anything to it:

    List 
    

    Basically, you use the second form (List) when you truly have a list that can contain any object and you want to be able to add elements to the list. You use the third form (List)when you receive the list as a method return value and you will iterate over the list but never add anything to it Never use the first form (List) in new code compiling under Java 5 or later.

    提交回复
    热议问题