简体   繁体   中英

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? Eg 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;
    }

}

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM