When to use generic methods and when to use wild-card?

前端 未结 9 2297
猫巷女王i
猫巷女王i 2020-11-22 10:32

I am reading about generic methods from OracleDocGenericMethod. I am pretty confused about the comparison when it says when to use wild-card and when to use generic methods.

9条回答
  •  温柔的废话
    2020-11-22 10:59

    Consider following example from The Java Programming by James Gosling 4th edition below where we want to merge 2 SinglyLinkQueue:

    public static  void merge(SinglyLinkQueue d, SinglyLinkQueue s){
        // merge s element into d
    }
    
    public static  void merge(SinglyLinkQueue d, SinglyLinkQueue s){
            // merge s element into d
    }
    

    Both of the above methods have the same functionality. So which is preferable? Answer is 2nd one. In the author's own words :

    "The general rule is to use wildcards when you can because code with wildcards is generally more readable than code with multiple type parameters. When deciding if you need a type variable, ask yourself if that type variable is used to relate two or more parameters, or to relate a parameter type with the return type. If the answer is no, then a wildcard should suffice."

    Note: In book only second method is given and type parameter name is S instead of 'T'. First method is not there in the book.

提交回复
热议问题