0

如果有人可以为我解决这个难题。我确定我错过了一些东西!

interface a { }
class b implements a { }
class c extends ArrayList<b> { }
class d {
    d(ArrayList<a> param) {}
}

class e {
    public static void main(String[] arg) {
         d newd = new d(new c());
    }
}

此代码有错误:错误 d(ArrayList<a>) is not applicable (actual argument c cannot be converted to ArrayList<a> by method invocation conversion)

当然,类c可以转换ArrayList<a>c扩展ArrayList<b>b实现a!我尝试过显式转换,但没有帮助。

class c extends ArrayList<b>改成toextends ArrayList<a>作为c集合的目的也没有意义b,界面a仅用于显示目的。classd也是一个通用显示类,它依赖于接口中表达的功能a,因此更改它也没有任何意义。

建议会很方便!

4

4 回答 4

3

This should suit your needs:

class d {
    d(ArrayList<? extends a> param) {
    }
}

c isn't an ArrayList<a> but an ArrayList<? extends a> since b is a subtype of a.

于 2013-02-20T15:51:40.347 回答
0

The problem is that an ArrayList is not the same thing as an ArrayList, even if b extends A. What would happen if D called param.add(new AImpl()), where AImpl was some other implementation of interface A?

For more details, see The Java Generics Tutorial section on inheritance.

(As an aside, it's also generally not a good idea to extend an ArrayList - most of the time, you want to be wrapping it, not extending it.)

于 2013-02-20T15:51:56.103 回答
0

It should be:

d(ArrayList<? extends a> param) {}

ArrayList is not a subclass of ArrayList because the former can have a's added to it while the latter cannot.

于 2013-02-20T15:52:08.483 回答
0

Please respect java naming conventions:

interface A {
}

class B implements A {
}

class C extends ArrayList<B> {
}

class D {

    D(ArrayList<A> param) {
    }
}

class E {

    public static void main(String[] arg) {
        D newd = new D(new C());
    }
}

So your assumption is that ArrayList<B> is castable to an ArrayList<A> as B implements A. This is not true, this is not how generics work. You simply cannot cast generic types. Try doing something like:

final ArrayList<Object> myNewArrayList = new ArrayList<String>();

To distill the problem.
You need to use bounded type parameters to solve this. Changing your D class to:

class D {

    D(ArrayList<? extends A> param) {        
    }
}

Would make it work as now you're saying: I want a collection of any type as long as it's an A.

于 2013-02-20T15:53:16.990 回答