Home > Back-end >  Lower and upper bound generic constraints on same wildcard
Lower and upper bound generic constraints on same wildcard

Time:04-12

Let's assume the following class hierarchy:

class A{}
class B extends A{}
class C extends B{}
class D extends C{}

In Java, it is possible to define wildcards with generics like this:

List<? extends A> aOrDown;//A or any subtype of A
List<? super D> dOrUp;//D or any supertype of D

Is it possible to bind the same wildcard to both an upper and lower bound?

I would imagine something like this:

List<? extends A super B> combined;
List<? extends A & super B> combined;

However, those seem to raise a compile-time error.

Is there any way to do bind a generic wildcard to a specific part of the class hierarchy?

I am interested whether this is possible in theory, I don't have a practical use-case for this.

CodePudding user response:

Section 4.5.1 of the JLS specifies the syntax for generic wildcards:

TypeArguments:
  < TypeArgumentList >
TypeArgumentList:
  TypeArgument {, TypeArgument}
TypeArgument:
  ReferenceType
  Wildcard
Wildcard:
  {Annotation} ? [WildcardBounds]
WildcardBounds:
  extends ReferenceType
  super ReferenceType

In here, WildcardBounds is written in square brackets. In Section 2.4 of the JLS, it is explained that in this context, square brackets indicate optional elements that can be put only once:

The syntax [x] on the right-hand side of a production denotes zero or one occurrences of x. That is, x is an optional symbol. The alternative which contains the optional symbol actually defines two alternatives: one that omits the optional symbol and one that includes it.

For bounded generic wildcards, this means that only one wildcard bound is permitted.

  • Related