在以下示例代碼中,兩個類EventA
和EventB
都實現了interface Historical
。當其中一個對象作爲參數傳遞時,Java可以自動將EventA
或EventB
轉換爲Historical
,如下面的examineEvent
方法所示。但是,當引入泛型時,Java不再可以投射,從List<EventA>
到List<Historical>
- 除非使用List<? extends Historical>
聲明目標函數(在此例中爲findClosestValidEventIndex
)。Java:使用接口指針進行泛型轉換
有人可以解釋爲什麼這一定是?在我看來,在通用中使用接口應該自動暗示<? extends Interface>
。
public class SampleApplication {
public interface Historical {
public DateTime getDate();
}
public static class EventA implements Historical {
private DateTime date;
@Override
public DateTime getDate() {
return date;
}
}
public static class EventB implements Historical {
private DateTime date;
@Override
public DateTime getDate() {
return date;
}
}
private static int findClosestValidEventIndex(List<Historical> history, DateTime when) {
// do some processing
return i;
}
private static int examineEvent(Historical event){
return j;
}
public static void main(String[] args) {
DateTime target = new DateTime();
// AOK
EventA a = new EventA(target);
int idy = examineEvent(a);
// Type Error --- Unless
List<EventA> alist = new ArrayList<EventA>();
int idx = findClosestValidEventIndex(alist, target);
}
}
好的,我明白了你的觀點。謝謝! – Colin 2011-05-31 17:37:43