Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

generics

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?

public class MyClass<T extends Number super Integer>
like image 655
Hosam Aly Avatar asked Mar 27 '10 19:03

Hosam Aly


1 Answers

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)
like image 144
Jon Skeet Avatar answered Nov 11 '22 13:11

Jon Skeet