[英]ArrayList<A> conversion to ArrayList<B> when A implements B Java
I'm quite new to Java, and I have a question about method invocation conversion. 我对Java很新,我对方法调用转换有疑问。
I've made a new class that extends ArrayList called ListableList - but that does not seem to be the problem. 我已经创建了一个新类,它扩展了名为ListableList的ArrayList - 但这似乎不是问题所在。
The problem is I have a method that looks like this 问题是我有一个看起来像这样的方法
public static void printList(ListableList<Listable> list, String seperator){
for(Listable item : list){
System.out.println(seperator);
System.out.println(item.toList());
}
System.out.println(seperator);
}
I call this method like this: 我这样称呼这个方法:
Output.printList(rules, "..");
Where rules is initialized as 规则初始化为
rules = new ListableList<Rule>();
And Rule implements Listable. 而Rule实现了Listable。
When I try to compile I get: 当我尝试编译时,我得到:
required: ListableList<Listable>,String
found: ListableList<Rule>,String
reason: actual argument ListableList<Rule> cannot be converted to ListableList<Listable> by method invocation conversion
Why is this, from what I've learned, this should work?? 从我所学到的,为什么这应该起作用? Thanks in advance:)
提前致谢:)
try to change your method signature of printList to: 尝试将printList的方法签名更改为:
public static void printList(ListableList<? extends Listable> list, String seperator){
Generic Types are not polymorphic, Ie, Listable<Listable>
is not a super type of List<Rule>
even though Rule is a sub-type
of Listable . 泛型类型不是多态的,即
Listable<Listable>
不是List<Rule>
的超类型,即使Rule是Listable的sub-type
。 You will have to use generics with upper bounded wildcards in your method signature to inform that your List can accept anything which is a sub-type of Listable. 您必须在方法签名中使用带有上限通配符的泛型来通知您的List可以接受任何可列表的子类型。 Note that you cannot add anything into your list if you use
Generics with upperbounded wildcards
. 请注意,如果将
Generics with upperbounded wildcards
使用,则无法在列表中添加任何内容。 Ie, 也就是说,
public static void printList(ListableList<? extends Listable> list, String seperator){
list.add(whatever); // is not allowed
Please use: 请用:
public static void printList(ListableList<? extends Listable> list, String seperator){
This means that list is a readonly collections, which contains subclasses of Listable. 这意味着list是一个只读集合,其中包含Listable的子类。
ListableList<Rule>
is not assign-compatible to ListableList<Listable>
because you can add non Rule objects to a ListableList<Listable>
. ListableList<Rule>
与ListableList<Listable>
不分配兼容,因为您可以将非Rule对象添加到ListableList<Listable>
。
Method declaration should be like printList(ListableList<? extends Listable> list, String seperator)
. 方法声明应该类似于
printList(ListableList<? extends Listable> list, String seperator)
。 Make it generic. 使它通用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.