简体   繁体   English

Java通配符在变量中具有多种类型

[英]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? 例如,我是否可以要求ArrayList仅接受实现两个不在同一类型层次结构中的两个不同接口的元素? 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. 我发现用该方法最容易看到:方法声明中从未使用过T2 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. 不幸的是,这些内部类型限制以这种方式成为了公共API的一部分,但这是我知道实现此工作的唯一方法。

If you don't want this, then try an inner, private interface ( AB ) in your example. 如果您不希望这样做,请在您的示例中尝试一个内部专用接口( AB )。

Java does not support multiple inheritance of classes - a class can extend only one single class (although a class can implement multiple interfaces). Java不支持类的多重继承-一个类只能扩展一个类(尽管一个类可以实现多个接口)。 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. 解决方案是创建一个同时扩展A和B的超级类型,然后将该类型传递给您的方法。 Something like 就像是

inteface C extends A,B{}

ArrayList<? extends C>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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