I'm currently studying on Effective Java Item 26, 27.
I learned about the captured type and looked up on Java Collections's reverse method,
and recognized that Java developers didn't use capture of type.
Looked up on GPT, and is replies that Java Developers might not have used it
because using type capture would increase the complexity of the code.
I kind of get the idea, but wonder this is the actual idea.
Understanding a captured type in Java (symbol '?')
Chapter 5. Conversions and Contexts
private static <T> void swapHelper(List<T> list, int i, int j) { // captured!
T temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
}
I know the method above (swapHelper) can be used. Just curious why they didn't used it.
The short answer -- generics are powerful and useful, but not every method needs them.
Think about it. You want to reverse a list. Not take something out, or put something back in. What would generics give you here?
If you wanted to extract something from the list, generics would allow you to maintain type-safety by ensuring that what comes out is of a particular type.
If you wanted to put something into the list, generics would allow you to ensure that the item you are inserting into the list is a type that the list can handle.
But in your situation, your items are already in the list, and you are not taking them out right at this moment. Specifically, the method's return type is void. Therefore, what do generics give you?
The answer is - nothing useful. At least not for this shuffle method. Like I said, they are useful elsewhere, but not for this shuffle method.
And you will see similar things for other methods. Consider the following.
Collections.disjoint(Collection<?> c1, Collection<?> c2) --> boolean
Collections.frequency(Collection<?> c1, Object o) --> int
For both of the above examples, they don't actually care about what the parameterized type is for each of the Collection
parameters. So, they simply put those aside, and focus on doing the actual task given. Also notice that their return types are unrelated to the parameterized types of each Collection
, so again, there is no benefit to be had by inserting a type parameter here.
Use generics where they are useful. They add complexity, so the only time you should include them is when the tradeoff actually gives you something good in exchange.