Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top