문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top