Can someone explain the declaration of these java generic methods?
- by Tony Giaccone
I'm reading "Generics in the Java Programming Language" by Gilad Bracha and I'm confused about a style of declaration. The following code is found on page 8:
interface Collection<E>
{
public boolean containsAll(Collection<?> c);
public boolean addAll(Collection<? extends E> c);
}
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!
}
My point of confusion comes from the second declaration. It's not clear to me what the purpose the <T> declaration serves in the following line:
public <T> boolean containsAll(Collection<T> c);
The method already has a type (boolean) associated with it.
Why would you use the <T> and what does it tell the complier?
I think my question needs to be a bit more specific.
Why would you write:
public <T> boolean containsAll(Collection<T> c);
vs
public boolean containsAll(Collection<T> c);
It's not clear to me, what the purpose of <T> is, in the first declaration of containsAll.