泛型范围“Enum&lt; T&gt; &安培; FOO&QUOT;和“Enum <?延伸Foo&gt;“。 [英] Is there a difference between the generic bounds &quot;Enum&lt;T&gt; &amp; Foo&quot; and &quot;Enum&lt;? extends Foo&gt;&quot;

查看:194
本文介绍了泛型范围“Enum&lt; T&gt; &安培; FOO&QUOT;和“Enum <?延伸Foo&gt;“。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个(有效的)通用边界:

 < T扩展Enum< T> &安培; MyInterface的> 

相同吗?




假设我有一个接口

  interface MyInterface {
void someMethod();
}

以及一些实现它的枚举:

 枚举MyEnumA实现MyInterface {
A,B,C;
public void someMethod(){}
}

枚举MyEnumB实现MyInterface {
X,Y,Z;
public void someMethod(){}
}

我想要一个实现不仅使用 MyInterface ,而且它也是一个枚举。 标准方法是通过一个交集约束:

  static class MyIntersectionClass< T extends Enum< T> &安培; MyInterface的> {
void use(T t){}
}

我发现这也是可行的:

  static class MyWildcardClass< T extends Enum< ;?扩展MyInterface>> {
void use(T t){}
}

,这个编译:

  public static void main(String [] args)throws Exception {
MyIntersectionClass< MyEnumA> a = new MyIntersectionClass< MyEnumA>();
a.use(MyEnumA.A);
MyWildcardClass< MyEnumB> b = new MyWildcardClass< MyEnumB>();
b.use(MyEnumB.X);
}

以上两种情况下的界​​限符合上述要求。 / p>

这两个边界之间是否有区别,如果是这样,哪一个比另一个更好?

  class MyEnumA扩展Enum< MyEnum2> {} 
class MyEnumB implements MyInterface {}

所以是的,在语义上它们是相同的但只是因为它是Enum。


Are these two (valid) generic bounds:

<T extends Enum<T> & MyInterface>
<T extends Enum<? extends MyInterface>>

the same?


Suppose I have an interface

interface MyInterface {
    void someMethod();
}

And some enums that implement it:

enum MyEnumA implements MyInterface {
    A, B, C;
    public void someMethod() {}
}

enum MyEnumB implements MyInterface {
    X, Y, Z;
    public void someMethod() {}
}

And I want to require that an implementation uses not only a MyInterface but also that it is an enum. The "standard" way is by an intersection bound:

static class MyIntersectionClass<T extends Enum<T> & MyInterface> {
    void use(T t) {}
}

But I've discovered that this also works:

static class MyWildcardClass<T extends Enum<? extends MyInterface>> {
    void use(T t) {}
}

With the above, this compiles:

public static void main(String[] args) throws Exception {
    MyIntersectionClass<MyEnumA> a = new MyIntersectionClass<MyEnumA>();
    a.use(MyEnumA.A);
    MyWildcardClass<MyEnumB> b = new MyWildcardClass<MyEnumB>();
    b.use(MyEnumB.X);
}

And the bound works as and intended and required by above for both cases.

Is there a difference between these two bounds, if so what, and is one "better" than the other?

解决方案

In this specific case there is no difference because Enums formal type parameter is effectively the self type. This is because one can not inherit from Enum like so:

class MyEnumA extends Enum<MyEnum2> {}
class MyEnumB implements MyInterface {}

So yes, semantically they're the same bound, but only because it's Enum.

这篇关于泛型范围“Enum&lt; T&gt; &安培; FOO&QUOT;和“Enum <?延伸Foo&gt;“。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆