What is the use and point of unbound wildcards generics in Java?

后端 未结 6 1862
渐次进展
渐次进展 2020-12-01 05:12

I don\'t understand what is the use of unbound wildcards generics. Bound wildcards generics with upper boundary makes perfect sense, be

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 05:58

    There are (rare) perfectly correct use cases for unbound wildcards. The SDK contains some of them.

    One example is a method that does a definite action on a list of any kind and does not return anything as rotate in Collections:

    static void rotate(List list, int distance)
    

    Another example is when you want to list the possible constructors for a class, the method is :

    Constructor[] getConstructors()
    

    Here it in not even possible to use a generic, because by definition the array will contain different constructor each with its own actual class. By contrast, the API does use a generic signature for getting one single constructor : Constructor getConstructor(Class... parameterTypes).

    The conclusion is that even if it is mainly used for compatibility with older code, there are still places where unbound wildcard generics are the correct way.

提交回复
热议问题