我想學習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謝謝我會牢記這一點。 –