SCJP題庫第182題
the class definitions:
class Animal{}
class Dog extends Animal{}
and the code:
public void go(){
ArrayList<Dog> aList = new ArrayList<Dog>();
takeList(aList);
}
//insert definition of the takeList() method here
Place the correct Compilation Result on each takeList() method definition to indicate whether or not the go() method would compile given that definition.
Ans:
解說:
ArrayList<Dog> aList = new ArrayList<Dog>();
上面這條敘述是宣告一個並新增一個aList陣列型式之串列物件,其中限定此串列儲存的物件必須為Dog類別,因此takeList這個方法要傳入aList這個串列物件,必須宣告接受內為Dog型態的串列物件:
ArrayList list 非泛型用法,不限定串列要放何種類別型態物件,所以可以接收aList
ArrayList<Animal> list 限定串列必須儲存Animal型態物件,如果要接受Animal子類別型態的話,要使用:ArrayList < ? extends Animal> 表示可代入任何是Animal 或 Animal的子類別型態
ArrayList <Object> 也是同上解釋
ArrayList <?> 表串列中可放任一型態物件
泛型請參考黃彬華講義12章
Comments