What is the difference between bounded wildcard and type parameters?

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

Is there a difference between

 Collection getThatCollection(Class type)

and

Colle         


        
2条回答
  •  感情败类
    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 c1 = getThatCollection(Integer.class);
    Collection 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, regardless of what the argument is:

    // Invalid statements
    Collection c1 = getThatCollection(Integer.class);   // invalid
    Collection c2 = getThatCollection(Double.class);   // invalid
    Collection cN = getThatCollection(Number.class);   // invalid
    
    // Valid statements
    Collection c3 = getThatCollection(Integer.class);  // valid
    Collection c4 = getThatCollection(Double.class);  // valid
    Collection 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.

提交回复
热议问题