I am reading about generic methods from OracleDocGenericMethod. I am pretty confused about the comparison when it says when to use wild-card and when to use generic methods. Quoting from the document.
interface Collection<E> { public boolean containsAll(Collection<?> c); public boolean addAll(Collection<? extends E> c); }
We could have used generic methods here instead:
interface Collection<E> { public <T> boolean containsAll(Collection<T> c); public <T extends E> boolean addAll(Collection<T> c); // Hey, type variables can have bounds too! }
[…] This tells us that the type argument is being used for polymorphism; its only effect is to allow a variety of actual argument types to be used at different invocation sites. If that is the case, one should use wildcards. Wildcards are designed to support flexible subtyping, which is what we're trying to express here.
Don't we think wild card like (Collection<? extends E> c);
is also supporting kind of
polymorphism? Then why generic method usage is considered not good in this?
Continuing ahead, it states,
Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type. If there isn't such a dependency, a generic method should not be used.
What does this mean?
They have presented the example
class Collections { public static <T> void copy(List<T> dest, List<? extends T> src) { ... }
[…]
We could have written the signature for this method another way, without using wildcards at all:
class Collections { public static <T, S extends T> void copy(List<T> dest, List<S> src) { ... }
The document discourages the second declaration and promotes usage of first syntax? What's the difference between the first and second declaration? Both seems to be doing the same thing?
Can someone put light on this area.
One other difference which is not listed here.
But the following will result in compile time error.
I will try and answer your question, one by one.
No. The reason is that the bounded wildcard has no defined parameter type. It is an unknown. All it "knows" is that the "containment" is of a type
E
(whatever defined). So, it cannot verify and justify whether the value provided matches the bounded type.So, it's no sensible to have polymorphic behaviours on wildcards.
The first option is better in this case as
T
is always bounded, andsource
will definitely have values (of unknowns) that subclassesT
.So, suppose that you want to copy all list of numbers, the first option will be
src
, essentially, can acceptList<Double>
,List<Float>
, etc. as there is an upper bound to the parameterized type found indest
.The 2nd option will force you to bind
S
for every type you want to copy, like soAs
S
is a parameterized type that needs binding.I hope this helps.
Wildcard method is also generic - you could call it with some range of types.
The
<T>
syntax defines a type variable name. If a type variable has any use (e.g. in method implementation or as a constraint for other type), then it makes sense to name it, otherwise you could use?
, as anonymous variable. So, looks like just a short-cut.Moreover, the
?
syntax is not avoidable when you declare a field:There are certain places, where wildcards, and type parameters do the same thing. But there are also certain places, where you have to use type parameters.
Taking your method as example, suppose you want to ensure that the
src
anddest
list passed tocopy()
method should be of same parameterized type, you can do it with type parameters like so:Here, you are ensured that both
dest
andsrc
have same parameterized type forList
. So, it's safe to copy elements fromsrc
todest
.But, if you go on to change the method to use wildcard:
it won't work as expected. In 2nd case, you can pass
List<Integer>
andList<Float>
asdest
andsrc
. So, moving elements fromsrc
todest
wouldn't be type safe anymore. If you don't need such kind of relation, then you are free not to use type parameters at all.Some other difference between using wildcards and type parameters are:
Wildcards support both upper and lower bounds, type parameters just support upper bounds. So, if you want to define a method that takes a
List
of typeInteger
or it's super class, you can do:but you can't use type parameter:
References:
Consider following example from The Java Programming by James Gosling 4th edition below where we want to merge 2 SinglyLinkQueue:
Both of the above methods have the same functionality. So which is preferable? Answer is 2nd one. In the author's own words :
"The general rule is to use wildcards when you can because code with wildcards is generally more readable than code with multiple type parameters. When deciding if you need a type variable, ask yourself if that type variable is used to relate two or more parameters, or to relate a parameter type with the return type. If the answer is no, then a wildcard should suffice."
Note: In book only second method is given and type parameter name is S instead of 'T'. First method is not there in the book.
As far as I understand, there is only one use case when wildcard is strictly needed (i.e. can express something that you can not express using explicit type parameters). This is when you need to specify a lower bound.
Apart from that however wildcards serve to write more concise code, as described by the following statements in the document you mention: