Java generics: wildcard<?> vs type parameter?

前端 未结 3 890
孤城傲影
孤城傲影 2020-12-04 16:59

I am refreshing my knowledge on Java generics. So I turned to the excellent tutorial from Oracle ... and started to put together a presentation for my coworkers. I came acro

3条回答
  •  Happy的楠姐
    2020-12-04 17:10

    Technically, there is no difference between

     void printObjects(List list) {
    

    and

    void printList(List list) {
    

    • When you are declaring a type parameter, and using it only once, it essentially becomes a wildcard parameter.
    • On the other hand, if you use it more than once, the difference becomes significant. e.g.

       void printObjectsExceptOne(List list, E object) {
      

      is completely different than

      void printObjects(List list, Object object) {
      

      You might see that first case enforces both types to be same. While there is no restriction in second case.


    As a result, if you are going to use a type parameter only once, it does not even make sense to name it. That is why java architects invented so called wildcard arguments (most probably).

    Wildcard parameters avoid unnecessary code bloat and make code more readable. If you need two, you have to fall back to regular syntax for type parameters.

    Hope this helps.

提交回复
热议问题