开发者

Is it possible to specify both upper and lower bound constraints on type parameters in Java?

开发者 https://www.devze.com 2022-12-24 03:51 出处:网络
Is it possible to specify both upper and lower bound constraints on type parameters in Java? I found a conversation in Sun\'s forum in which this issue was discussed (apparently before the generics f

Is it possible to specify both upper and lower bound constraints on type parameters in Java?

I found a conversation in Sun's forum in which this issue was discussed (apparently before the generics feature was finalized), but there was no final answer.

In summary, is there a valid syntax to do the following?

p开发者_开发技巧ublic class MyClass<T extends Number super Integer>


I don't believe so - as far as I can tell from the language specification, "super" is only valid for wildcard types in the first place. The syntax for wildcards also suggests you can only have one wildcard bound, too - so you can't use something like this either:

// Invalid
void foo(List<? extends Foo super Bar> list)

Even though both of these are okay:

// Valid
void foo(List<? extends Foo> list)

// Valid
void foo(List<? super Bar> list)

As noted in comments, it's possible to have multiple upper bounds - but only for type parameters and cast expressions. For example:

// Valid
<T extends Number & Comparable> void foo(List<T> list)


From Oracle's tutorial:

Note: You can specify an upper bound for a wildcard, or you can specify a lower bound, but you cannot specify both.


you can't specify both at the same time but you can achieve like given code.

class Family<F> {
    F f;

    public void setF(F f) {
        this.f = f;
    }
}

class GrandParent {
}

class Parent extends GrandParent {
}

class Child extends Parent {
}

private <T extends Parent> void foo(Family<? super T> list) {
    list = new Family<Parent>(); // Allows
    list = new Family<GrandParent>(); // Allows
    list = new Family<Child>(); // Not Allows

    list.setF(new GrandParent()); // Not Allows
    list.setF(new Parent()); // Not Allows
    list.setF(new Child()); // Not Allows
}

public void bar() {
    foo(new Family<GrandParent>()); // Allows
    foo(new Family<Parent>()); // Allows
    foo(new Family<Child>()); // Allows
}
0

精彩评论

暂无评论...
验证码 换一张
取 消