Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type parameter vs unbounded wildcard

Tags:

java

generics

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!

like image 282
dbf Avatar asked Aug 09 '13 07:08

dbf


1 Answers

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.

like image 184
xwoker Avatar answered Sep 21 '22 13:09

xwoker