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

后端 未结 12 1889
你的背包
你的背包 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 17:44

    In my own simple terms:

    List

    Would declare an ordinary collection, can hold any type, and will always return Object.

    List

    Will create a list that can hold any type of object, but can only get assigned a another List

    For instance this doesn't work;

    List l = new ArrayList();
    
    
    

    Of course you can add anything but only can pull Object.

    List l = new ArrayList();
    
    l.add( new Employee() );
    l.add( new String() );
    
    Object o = l.get( 0 );
    Object o2 = l.get( 1 );
    
    
    

    Finally

    List

    Will let you assign any type, including

    List  l = new ArrayList(); 
    List  l2 = new ArrayList();
    

    This would be called collection of unknown and since the common denominator of unknown is Object you will be able to fetch Objects ( a coincidence )

    The importance of unknown comes when its used with subclassing:

    List l = new ArrayList(); // compiles
    
    List l = new ArrayList(); // doesn't,
    // because String is not part of *Collection* inheritance tree. 
    

    I hope using Collection as the type doesn't create confusion, that was the only tree that came to my mind.

    The difference here, is that l is a collection of unknow that belongs to the Collection hierarchy.

    提交回复
    热议问题