[英]Java generics question
So I have 3 classes. 所以我有3节课。
Abstract class A
Class B extends class A
independent Class C
In class D that contains the main method, I create a list of instances of class B 在包含main方法的D类中,我创建了一个B类实例的列表
List<B> b = methodCall(); // the method returns a list of instances of class B
Now in class CI have one method that is common to both A and B, and hence I don't want to duplicate it. 现在在类CI中有一个方法对A和B都是通用的,因此我不想复制它。 I want to have one method that takes as input an instance of class A, as follows:
我想有一个方法,将A类的实例作为输入,如下所示:
public void someMethod(List<A> a)
However, when I do: 但是,当我这样做时:
C c = new C();
c.someMethod(b);
I get an error that some-method is not applicable for the argument List<B>
, instead it's expecting to get List<A>
. 我得到一个错误,some-method不适用于参数
List<B>
,而是期望得到List<A>
。
Is there a good way to fix this problem? 有没有一种解决这个问题的好方法? Many thanks!
非常感谢!
If you have a method which expects List<A>
, and a class B extends A
, and you want to pass this method a List<B>
, then you should declare the method as: 如果你有一个期望
List<A>
的方法,并且一个B extends A
类B extends A
,并且你希望将这个方法传递给List<B>
,那么你应该将该方法声明为:
public void someMethod(List<? extends A> list)
This allows the list passed to the method to be a List of A or anything that extends B. 这允许传递给方法的列表是A的列表或任何扩展B的列表。
Note though that you will not be able to tell the exact type of ?
请注意,您将无法确定具体类型
?
passed into the method. 传递给方法。
Also, if you have duplicated methods between two classes, that's probably a sign that something is off with your design. 此外,如果您在两个类之间有重复的方法,那可能表明您的设计出现了问题。
public void someMethod(List<? extends A> a){ //...
In your method signature you have List<A> a
which means it only accepts a list of objects of type A
. 在方法签名中,您有
List<A> a
,这意味着它只接受A
类对象的列表。 What you need is something that accepts a list of A
and any subtype of A
(or a family of subtypes of A). 你需要的东西是接受
A
的列表和A
any subtype of A
(或any subtype of A
一个子类型)。
What you need is this: 你需要的是这个:
public void someMethod(List<? extends A> list) {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.