Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

java - Type parameter vs unbounded wildcard

From Effective Java Chapter 5 (generics):

// Two possible declarations for the swap method
public static <E> void swap(List<E> list, int i, int j);
public static void swap(List<?> list, int i, int j);

Which of these two declarations is preferable, and why? In a public API, the second is better because it’s simpler. You pass in a list — any list — and the method swaps the indexed elements. There is no type parameter to worry about. As a rule, if a type parameter appears only once in a method declaration, replace it with a wildcard.

I don't understand, why second option is simplier for client of my API? I can pass the same parameters to first and second methods. Also second one requires helper method for wildcard capture. Could someone explains why second is recommended? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Java Generics FAQ is a great source to answer these kind of questions and the "wildcard vs. generic" one is discussed at length in Which one is better: a generic method with type parameters or a non-generic method with wildcards? and the subsequent Case Studies.

Angelika Langer comes to the conclusion:

Conclusion: In all these examples it is mostly a matter of taste and style whether you prefer the generic or the wildcard version. There is usually trade-off between ease of implementation (the generic version is often easier to implement) and complexity of signature (the wildcard version has fewer type parameters or none at all).

Simpler method signature -> easier to understand (even if both are used the same way) -> good in public API (tradeoff: more complex implementation)

But the whole thing is a lightweight issue and in my experience is consistency over the whole API much more important than which style you use.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...