2009年2月24日 星期二

第201題

Given:
1. import java.util.*;
2. class A{}
3. class B extends A{}
4. public class Test{
5. public static void main(Strang[] args){
6. List<> listA = new LinkedList<>();
7. List<> listB = new LinkedList<>();
8. List<> listO = new LinkedList<>();
9. //insert code here
10. }
11. public static void m1(List list){}
12. public static void m2(List<> list){}
Place a result onto each method call to indicate what would happen if the method call were inserted at line 9.

Note: Results can be used more than once.

Method Calls:
m1(listA); m2(listA);
m1(listB); m2(listB);
m1(listO); m2(listO);


Result :
Does not compile.
Compiles and runs without error.
An exception is thrown at runtime.


答案:
m1(listA); Compiles and runs without error.
m1(listB); Compiles and runs without error.
m1(listO); Does not compile.
m2(listA); Compiles and runs without error.
m2(listB); Does not compile.
m2(listO); Does not compile.
參考:12-3 泛型

-------------------------------
泛型在方法傳遞值時, 並需要完成相等 除非是用 ? extends 或 ? super
void m1(List list){} //開放類別A 或其子類別.
m1(listA); // A 或 A的子類別.
m1(listB); // B有繼承A並且A的子類別.
m1(listO); // Object 不是 A的子類別.


m2(List<> list ) {} //只開放 類別A

m2(listA); . // 傳遞類別為 A
m2(listB); . // 雖然有繼承A , 但是m2 並沒有開放子類別.
m2(listO); . // listO 類別為 Object, 所以失敗

沒有留言:

張貼留言