Understanding upper and lower bounds on ? in Java Generics

后端 未结 6 483
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 01:45

I am really having a tough time understanding the wild card parameter. I have a few questions regarding that.

  1. ? as a type parameter can only

6条回答
  •  一整个雨季
    2020-11-29 02:09

    First of all T or E or K or whatever are not fixed names. They are just type variables, and you decide the name for them. T, E, K are just examples but you could call it Foo or whatever.

    Now going to your first question: since the wildcard ? represents the "any and unknown" type, the unspecified one, it doesn't make any sense to declare a class generic over an unspecified type. It's useful to have wildcard in parameters of methods or in variables when you don't care about the type.

    Now regarding your second question: the lower bound gives even more flexibility to your generic methods. both extends and super are the opposite:

    • ? extends T: an unknown type which is a subtype of T
    • ? super T: an unknown type which is a super type of T

    The latter can be useful when you want to accept a type that is compatible with T (so that T is-a that type). A practical example can be found here.

提交回复
热议问题