【问题标题】:Aren't <U, T extends U> and <T, U super T> the same?<U, T extends U> 和 <T, U super T> 不一样吗?
【发布时间】:2012-10-03 09:35:42
【问题描述】:

我对以下两个方法声明感到困惑:

    private <U, T extends U> T funWorks(T child, U parent) {
      // No compilation errors
    }

    private <T, U super T> T funNotWorks(T child, U parent) {
      // compilation errors    
    }

以上两个都不应该有效吗?类比 如果 U 是 T 的父级,则 T 是 U 的子级。那为什么第二个会出现编译错误呢?

编辑:: 我认为,T extends TT super T 都是有效的。对吧?

【问题讨论】:

  • 我怀疑T extends U 表示T &gt;= U 其中U super T 表示U &lt; T,但我可能是错的......
  • 你应该看看this thread
  • @DayS:差不多? - 任何事物。我明白那个。但是如果是 T 和 U 呢?

标签: java generics collections type-parameter


【解决方案1】:
  • 类型参数(您的示例)只能使用扩展(JLS #4.4):
TypeParameter:
    TypeVariable TypeBoundopt

TypeBound:
    extends TypeVariable
    extends ClassOrInterfaceType AdditionalBoundListopt

AdditionalBoundList:
    AdditionalBound AdditionalBoundList
    AdditionalBound

AdditionalBound:
    & InterfaceType
  • 通配符可以使用extendssuper (JLS #4.5.1):
TypeArguments:
    < TypeArgumentList >

TypeArgumentList: 
    TypeArgument
    TypeArgumentList , TypeArgument

TypeArgument:
    ReferenceType
    Wildcard

Wildcard:
    ? WildcardBoundsopt

WildcardBounds:
    extends ReferenceType
    super ReferenceType

【讨论】:

    【解决方案2】:

    您不能将命名泛型与 super 绑定。另请参阅thisstackoverflow 发布。

    【讨论】:

      猜你喜欢
      • 2019-01-26
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-30
      相关资源
      最近更新 更多