What is the difference between A and A<? extends B>?

后端 未结 4 1859
借酒劲吻你
借酒劲吻你 2020-12-23 10:57

I am a new java learner. Recently I was reading Generic programming and got my self confused with this...

A and A
         


        
4条回答
  •  生来不讨喜
    2020-12-23 11:20

    Generics is a complicated subject in general, and especially in Java. But basically the difference is:

    T extends B

    There is a specific type T, it is just limited to being B or a subclass of B, but it is a specific know type. Any plain old generic declaration is like saying: By saying T extends B, we are saying that T is more limited than any object, it has to specifically be a type of B.

    ? extends B

    This means that the generic type is unknown, exactly, but what we can say about it is that it extends B. It may be B, it may be a subclass of B. With a wildcard and the word extends, it means that you can get B out of the object, but you cannot put anything in the object in a type safe way. (? super B means the opposite - you can put something in a method parameter that is a B or a superclass of B, but you cannot be sure what the return value of a method would be.)

提交回复
热议问题