Java wildcarding with multiple types in variable

I know it is possible to wildcard with multiple types in case of methods and classes but what about variables? E.g. can I require an ArrayList to only take elements that implement both of two different interfaces that are not in the same type hierarchy? See code below for what I am trying to do.

import java.util.ArrayList;

interface A {}
interface B{}
interface AB extends A, B{}

class D <T extends A & B> {    //This works but this is a class
    T variable;
}

public class C {

    ArrayList<AB> myList1 = new ArrayList<AB>();  // compiles
    ArrayList<? extends AB> myList3 =  new ArrayList<AB>(); //compiles

   //The following does not compile.
   ArrayList<? extends A & B> myList4 =  new ArrayList<AB>();

    //This works but this is a method: 
    public static <T extends A & B> T someMethod(ArrayList<? extends T> list) {
        return null;
    }

}

Answers


Yes:

class C<T extends A & B> {
    ArrayList<T> field;

    public <T2 extends A & B> void method() {
        ArrayList<T2> localVar;
    }
}

It looks a bit odd that you have to define an alias for the generic "type" outside of the scope where you use it but it works. I find it's easiest to see with the method: T2 is never used in the method declaration. It's solely used inside of the method.

It's unfortunate that these inner type limits become part of the public API this way but that's the only way I know to make this work.

If you don't want this, then try an inner, private interface (AB) in your example.


Java does not support multiple inheritance of classes - a class can extend only one single class (although a class can implement multiple interfaces). Hence I believe the

ArrayList<? extends A & B> 

doesn't work.

Solution would be create a super type that extends both A & B and then pass the type to your method. Something like

inteface C extends A,B{}

ArrayList<? extends C>

Need Your Help

How to return XML from SQL Server 2008 that is structured with multiple selections sharing a common parent

sql sql-server xml sql-server-2008 sqlxml

I've tried using "FOR XML PATH", "FOR XML EXPLICIT" and "FOR XML AUTO" but the data is never structured with the correct heirarchy.