简体   繁体   English

Java 中的通配符,用于从相同 class 继承的类

[英]WildCard in Java for classes that inherit from same class

Having the next classes in Java:在 Java 中有下一个类:

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

class ClassMethods {
    A method1(ArrayList<? extends A> list) {
        return list.get(1);
    }
    void method2(ArrayList<?> list, A el) {
        list.add(el);
    }

    void method3(A elem) {
        ArrayList<A> listA = new ArrayList<A>();
        listA.add(new A()); listA.add(new A());
        ArrayList<B> listB = new ArrayList<B>();
        listA.add(new B()); listB.add(new B());
        ArrayList<C> listC = new ArrayList<C>();
        listC.add(new C()); listC.add(new C());

        this.method1(listA);
        this.method1(listB);
        this.method1(listC);

        this.method2(listA, elem);
        this.method2(listB, elem);
        this.method2(listC, elem);
    }
}

Is there any way to make method2 working?有什么方法可以让method2工作吗? Without overloading it.无需超载。 Because we write in the list, we may need a "? super x" specifier.因为我们写在列表中,我们可能需要一个“?super x”说明符。 But "super B" will not work for a C class for example.但例如,“超级 B”不适用于 C class。 So I think the only possibility to make it work is to have one with "? super B" and an overload with "? super C".所以我认为让它工作的唯一可能性是让一个带有“?super B”和一个带有“?super C”的重载。 I can change only the "<...>" part of it, this is how the problem was proposed, and to explain if it can not be done.我只能更改它的“<...>”部分,这就是问题的提出方式,并解释如果它不能完成。

Suppose A was Object and B was String , would you expect to be able to take a List<String> strs , Object item and call strs.add(item) ?假设AObjectBString ,您是否希望能够获取List<String> strsObject item并调用strs.add(item)

The closest thing you could do is dd a type parameter.您可以做的最接近的事情是 dd 类型参数。

<T> void method2(ArrayList<? super T> list, T el) {
    list.add(el);
}

but that is the wrong way around.但这是错误的方法。

If you try to inline method2 you will see the error more directly.如果您尝试内联method2 ,您将更直接地看到错误。

    listA.add(elem);
    listB.add(elem); // No chance.
    listC.add(elem); // No chance.
    

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

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