Why generic type is not applicable for argument extends super class for both?

后端 未结 5 1165
迷失自我
迷失自我 2020-12-03 17:44

Here is the problem that I have been being tried to find the solution.

We have two class definitions. One of two extends other one.

    class T{}         


        
5条回答
  •  孤街浪徒
    2020-12-03 18:24

    List indicates that anything can comes out of it can be cast to T, so the true list could be any of the following:

    • List
    • List
    • List
    • etc

    You can see that even a new T cannot safely be added to such a collection because it could be a List which T cannot be put into. As such, such List cannot have non null entries added to them.

    In this case you may simply want List

    So why would you ever use this?!

    This contravariance can be useful for method parameters or returns, in which a collection will be read, rather than added to. A use for this could be to create a method that accepts any collection that holds items that are T, or extend T.

    public static void processList(Collection list){
        for(Vector3d vector:list){
            //do something
        }
    }
    

    This method could accept any collection of objects that extends Vector3d, so ArrayList would be acceptable.

    Equally a method could return such a collection. An example of a use case is described in Returning a Collection from a method that specifies that it returns Collection.

提交回复
热议问题