Java Collection Interface addAll() method signature
What difference would it make if Java Collection Interface has addAll method signature like this
<T extends E> boolean addAll(Collection开发者_Python百科<T> c);
rather than
boolean addAll(Collection<? extends E> c);
?
Thanks
-Abidi
In this case, having <?>
or <T>
is equivalent for users of addAll
.
I think that the former notation was used for clarity, because using <T>
makes the signature of addAll
more complicated.
Take this test interface:
public interface DumbTestInterface<E> {
<T extends E> boolean addAll1(Collection<T> c);
boolean addAll2(Collection<? extends E> c);
}
Here's the byte code:
// Compiled from DumbTestInterface.java (version 1.6 : 50.0, no super bit)
// Signature: <E:Ljava/lang/Object;>Ljava/lang/Object;
public abstract interface rumba.dumba.DumbTestInterface {
// Method descriptor #6 (Ljava/util/Collection;)Z
// Signature: <T:TE;>(Ljava/util/Collection<TT;>;)Z
public abstract boolean addAll1(java.util.Collection arg0);
// Method descriptor #6 (Ljava/util/Collection;)Z
// Signature: (Ljava/util/Collection<+TE;>;)Z
public abstract boolean addAll2(java.util.Collection arg0);
}
As you can see there's no difference in the resulting byte code (apart from the generated debug code). So if the two versions are equivalent, you might as well stick with the version that's easier to understand.
The thing is, the T
in <T extends E> boolean addAll(Collection<T> c)
is completely unnecessary, because addAll
doesn't care what specific subtype of E
the collection it's given contains. All it cares is that the collection it's given contains some subtype of E
, which is exactly what Collection<? extends E>
means.
You shouldn't introduce unnecessary generic types to a method.
If you used an explicit class T, then you could not pass a wildcarded collection to the method, which is something that you may want to do and should be able to.
Basically, when the type variable T
is only going to be used in one place somewhere in the types of the parameters, you can safely change it to ?
.
I don't think that would compile. A method cannot have two return types (<T>
and boolean
) at the same time.
精彩评论