Kiran
Kiran

Reputation: 5526

What is the difference between "? extends E" and "T extends E"?

I am new to java and am trying to understand the curious syntax below from Java Generics and Collections book.. (I worked extensively with C++ templates and hence can claim to understand the basics of generic programming and the probable gotchas):

interface Collection <E> {
  ...
  public boolean addAll(Collection<? extends E> c);
  ...
}

Why can't the above be written as:

interface Collection <E> {
  ...
  public boolean addAll(Collection<T extends E> c);
  ...
}

What is the difference? Is it just the language restriction or is there any difference under the hood?

Upvotes: 3

Views: 1038

Answers (2)

Louis Wasserman
Louis Wasserman

Reputation: 198023

It could be written as

 public <T extends E> boolean addAll(Collection<T> c)

but there would be no point. There's no need to name that parameter.

Upvotes: 8

Luciano
Luciano

Reputation: 8582

That would make sense if the method would return something of type T. Then you could match both types. But as it just returns a boolean, you don't need to do that. Then there is no need to set a name T and it remains just as a question mark.

Let's say addAll takes a filter:

public <T extends E> boolean addAll(Collection<T> c, Predicate<T> aFilter);

Now you know that the Predicate has a generic type that can operate on the collection c.

Upvotes: 3

Related Questions