Java:使用接口指针转换为通用 [英] Java: Casting to Generic with Interface Pointers
问题描述
在下面的示例代码中,两个类 EventA
和 EventB
都实现
。 Java可以自动将 EventA
或 EventB
转换为历史
这些对象之一作为参数传递,如下面的 examineEvent
方法中。但是,当引入一个泛型时,Java不再能够强制转换。从列表
)使用列表< Historical>
- 除非目标函数c> findClosestValidEventIndex List< ;? extends Historical>
。
In the following sample code two classes EventA
and EventB
both implement the interface Historical
. Java can automatically cast an EventA
or EventB
to Historical
when one of these objects is passed as a parameter, as in the examineEvent
method below. However, Java is no longer able to cast when a generic is introduced ie. from List<EventA>
to List<Historical>
-- Unless the target function (in this case findClosestValidEventIndex
) is declared using List<? extends Historical>
.
有人可以解释为什么必须这样做吗?在我看来,在一个通用的接口的使用应该自动暗示<?扩展接口>
。
Can someone explain why this must be? It seems to me that the very use of an interface in a generic should automatically imply the <? 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);
}
}
推荐答案
列表< EventA>
不是 列表<历史>
。想象:
List<EventA> list = ...;
List<Historical> h = (List<Historical>) list;
h.add(new EventB()); //type-safety of list is compromised
for (EventA evt : list) { // ClassCastException - there's an EventB in the lsit
...
}
列表< ;? extends Historical>
意味着历史的一个特定子类型的列表,并且您不能添加任何东西,因为在编译时你不知道什么类型。
List<? extends Historical>
means "a list of a one specific subtype of Historical", and you cannot add anything to it, because at compile time you don't know what the type is.
这篇关于Java:使用接口指针转换为通用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!