我是 Java 的新手,我有一个关于方法调用转换的问题。
我创建了一个扩展 ArrayList 的新类,名为 ListableList - 但这似乎不是问题所在。
问题是我有一个看起来像这样的方法
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);
}
我这样调用这个方法:
Output.printList(rules, "..");
规则初始化为
rules = new ListableList<Rule>();
Rule 实现了 Listable。
当我尝试编译时,我得到:
required: ListableList<Listable>,String
found: ListableList<Rule>,String
reason: actual argument ListableList<Rule> cannot be converted to ListableList<Listable> by method invocation conversion
据我所知,为什么这应该有效?? 提前致谢:)
最佳答案
尝试将 printList 的方法签名更改为:
public static void printList(ListableList<? extends Listable> list, String seperator){
通用类型不是多态的,即Listable<Listable>
不是 List<Rule>
的父类(super class)型尽管 Rule 是 sub-type
可列出。您将不得不使用 generics with upper bounded wildcards在您的方法签名中告知您的列表可以接受任何可列表的子类型。请注意,如果您使用 Generics with upperbounded wildcards
,则无法将任何内容添加到列表中。 .即,
public static void printList(ListableList<? extends Listable> list, String seperator){
list.add(whatever); // is not allowed
有用的链接
关于java - 当 A 实现 B Java 时,ArrayList<A> 转换为 ArrayList<B>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15338548/