Whats the use of saying <? extends SomeObject> instead of

后端 未结 5 1756
陌清茗
陌清茗 2020-11-27 18:54

So I was looking over some Java code and stumbled upon:

List l;

basically this list accepts all objects that ar

5条回答
  •  情深已故
    2020-11-27 19:40

    The key link you want to read is http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html which explains Generic wildcard in detail.

    The List is not the same as List. Observe the following

    List x = new ArrayList();
    List y = new ArrayList();
    // x = y; Will throw Compilation exception
    List z = y; //will pass compilation
    
    
    

    You may want to observe that you can add say a String to both the x and the y list however it will be useful when you write say a library function (such as the printCollection in the example shown in the link) rather than accepting a Collection in which case a user cannot pass his list of strings that he has to your method, if you accept Collection then the user can pass his Collection, Collection etc without having to explicitly create another list.

    提交回复
    热议问题