Can someone explain the declaration of these java generic methods?

Posted by Tony Giaccone on Stack Overflow See other posts from Stack Overflow or by Tony Giaccone
Published on 2011-01-14T15:13:28Z Indexed on 2011/01/14 18:53 UTC
Read the original article Hit count: 239

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about java

Related posts about generics