Why should I use wildcards, preferring type parameters?

I read Effective Java 2nd Edition and in Point 28: Use limited wildcards to increase API flexibility , the following exists:

// 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 ads is preferable and why? In the public API, the second is better because it is simpler. You go to a list — any list — and the method changes the indexed items. There is no type of parameter to worry about. Typically, if a type parameter appears only once in a method declaration, replace it with a wildcard.

I am testing it with an parameter of unlimited type, and I see no flaws, I can pass any list, and I had no problems with the type parameter, in fact the parameter of unlimited type was better, because I do not need an assistant method explaining the sequence :

There is a way to implement this method without resorting to the unsafe cast or raw type. The idea is to write a private helper method for capturing a wildcard type. The helper method must be a general method to capture the type. Here's what it looks like:

public static void swap(List<?> list, int i, int j) {
    swapHelper(list, i, j);
}
// Private helper method for wildcard capture
private static <E> void swapHelper(List<E> list, int i, int j) {
    list.set(i, list.set(j, list.get(i)));
}

Finally, here is my implementation using a type parameter:

 public static <E> void swap(List<E> list, int i, int j) {
        list.set(i, list.set(j, list.get(i)));
  }

and use:

List<Object> integers = (...)
swap(integers, 1,2);

So why should I use a wildcard?

Question: why is the second method easier? I do not understand why! Am I missing details? I really want to understand what Bloch meant.

+4
1

, - ( , ).

, , . , .

API , ... . , , .

... ....

API, , API .

, , E - , - swap() List, ? "" E . 52: .

, , API. , - .

- , , , , , . , , , , .

+2

All Articles