What is the difference between bounded wildcard and type parameters?

前端 未结 2 640
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 15:40

Is there a difference between

 Collection getThatCollection(Class type)

and

Colle         


        
相关标签:
2条回答
  • 2020-11-27 15:42

    In this particular case, no. however the second option is more flexible since it would allow you to return a collection that contains elements of a different type (even though it would also be a Number) than the type contained by the collection parameter.

    Concrete example:

    Collection<? extends Number> getRoot(Class<? extends Number> number){ 
        ArrayList<Integer> result=new ArrayList<Integer>();
        result.add(java.util.Math.round(number); 
        return result) 
    }
    
    0 讨论(0)
  • 2020-11-27 15:53

    They expose different interfaces and contract for the method.

    The first declaration should return a collection whose elements type is the same of the argument class. The compiler infers the type of N (if not specified). So the following two statements are valid when using the first declaration:

    Collection<Integer> c1 = getThatCollection(Integer.class);
    Collection<Double> c2 = getThatCollection(Double.class);
    

    The second declaration doesn't declare the relationship between the returned Collection type argument to the argument class. The compiler assumes that they are unrelated, so the client would have to use the returned type as Collection<? extends Number>, regardless of what the argument is:

    // Invalid statements
    Collection<Integer> c1 = getThatCollection(Integer.class);   // invalid
    Collection<Double> c2 = getThatCollection(Double.class);   // invalid
    Collection<Number> cN = getThatCollection(Number.class);   // invalid
    
    // Valid statements
    Collection<? extends Number> c3 = getThatCollection(Integer.class);  // valid
    Collection<? extends Number> c4 = getThatCollection(Double.class);  // valid
    Collection<? extends Number> cNC = getThatCollection(Number.class);  // valid
    

    Recommendation

    If indeed there is a relationship between the type between the returned type argument and the passed argument, it is much better to use the first declaration. The client code is cleaner as stated above.

    If the relationship doesn't exist, then it is still better to avoid the second declaration. Having a returned type with a bounded wildcard forces the client to use wildcards everywhere, so the client code becomes clattered and unreadable. Joshua Bloch emphisize that you should Avoid Bounded Wildcards in Return Types (slide 23). While bounded wildcards in return types may be useful is some cases, the ugliness of the result code should, IMHO, override the benefit.

    0 讨论(0)
提交回复
热议问题