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

前端 未结 9 2299
猫巷女王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 11:07

    I will try and answer your question, one by one.

    Don't we think wild card like (Collection c); is also supporting kind of polymorphism?

    No. The reason is that the bounded wildcard has no defined parameter type. It is an unknown. All it "knows" is that the "containment" is of a type E (whatever defined). So, it cannot verify and justify whether the value provided matches the bounded type.

    So, it's no sensible to have polymorphic behaviours on wildcards.

    The document discourages the second declaration and promotes usage of first syntax? What's the difference between the first and second declaration? Both seems to be doing the same thing?

    The first option is better in this case as T is always bounded, and source will definitely have values (of unknowns) that subclasses T.

    So, suppose that you want to copy all list of numbers, the first option will be

    Collections.copy(List dest, List src);
    

    src, essentially, can accept List, List, etc. as there is an upper bound to the parameterized type found in dest.

    The 2nd option will force you to bind S for every type you want to copy, like so

    //For double 
    Collections.copy(List dest, List src); //Double extends Number.
    
    //For int
    Collections.copy(List dest, List src); //Integer extends Number.
    

    As S is a parameterized type that needs binding.

    I hope this helps.

提交回复
热议问题