简体   繁体   English

“有什么区别?” 延伸E“和”T延伸E“?

[英]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): 我是java新手,我正在尝试从Java Generics和Collections书中理解下面的奇怪语法。(我​​广泛使用C ++模板,因此可以声称理解泛型编程的基础知识和可能的陷阱):

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. 如果方法返回类型为T的东西,那将是有意义的。然后你可以匹配这两种类型。 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. 然后,不需要设置名称T,它仍然只是一个问号。

Let's say addAll takes a filter: 假设addAll采用过滤器:

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. 现在你知道Predicate有一个可以在集合c上运行的泛型类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM