我想学习Java中的通配符。在这里,我试图修改printCollection
方法,以便它只会使用延伸AbstractList
的类。它显示评论中的错误。我试图用一个ArrayList
的对象,它工作正常。我正在使用Java 7.ArrayList的对象和抽象
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
public class Subtype {
void printCollection(Collection<? extends AbstractList<?>> c) {
for (Object e : c) {
System.out.println(e);
}
}
public static void main(String[] args) {
Subtype st= new Subtype();
ArrayList<String> al = new ArrayList<String>();
al.add("a");
al.add("n");
al.add("c");
al.add("f");
al.add("y");
al.add("w");
//The method printCollection(Collection<? extends AbstractList<?>>) in the type Subtype is not applicable for the
// arguments (ArrayList<String>)
st.printCollection(al);
}
}
是否有一个特定的原因,你为什么只希望允许列表扩展'AbstractList'而不是所有实现'List'接口(契约)的列表?通过指定'AbstractList',您可以将代码耦合到特定的实现。只要有可能,你应该编码到接口而不是实现。 –
@MickMnemonic谢谢我会牢记这一点。 –