gline9
gline9

Reputation: 73

Lower and Upper Bound for Java Wildcard Type

I've looked around and so far haven't seen any way of having both a lower and upper bound on the same wildcard type in java. I'm not sure if it is possible and am leaning towards it being a current limitation of wildcards in java.

An example of what I'm looking for is below.

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

public static void main(String[] args)
{
    List<A> a = Arrays.asList(new A());
    List<B> b = Arrays.asList(new B());
    List<C> c = Arrays.asList(new C());
    List<D> d = Arrays.asList(new D());

    extendsParam(a); // error as A is not assignable to B
    extendsParam(b);
    extendsParam(c); 
    extendsParam(d); // 3 previous ok as they can produce B

    superParam(a);
    superParam(b);
    superParam(c); // 3 previous ok as they can consume C
    superParam(d); // error as C is not assignable to D

    extendsSuperParam(a); // error as A is not assignable to B
    extendsSuperParam(b);
    extendsSuperParam(c); // 2 previous ok as they can consume C and produce B
    extendsSuperParam(d); // error as C is not assignable to D
}

public static void extendsParam(List<? extends B> blist)
{
    B b = blist.get(0);
    blist.add(new C()); // error
}

public static void superParam(List<? super C> clist)
{
    B b = clist.get(0); // error
    clist.add(new C());
}

public static void extendsSuperParam(List<???> bclist)
{
    B b = bclist.get(0); // ok
    bclist.add(new C()); // ok
}

Looking at the WildcardType.java class for the generic type information it looks like it supports defining a type with that information. However, I cannot find a way to create such a type in the language.

Is there something that I'm missing or is this a type that is currently impossible to describe with the java language?

Upvotes: 6

Views: 640

Answers (1)

djk
djk

Reputation: 36

This can't be done according to the Oracle Docs:

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

Upvotes: 2

Related Questions