Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

java - Is there a difference between the generic bounds "Enum<T> & Foo" and "Enum<? extends Foo>"

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...