泛型Java:使用父类作为类型参数的构造函数
我有一个带有树形图字段和构造函数的类时间轴,如下所示:
public class Timeline{
private TreeMap<DateTime, Schedulable> schedule;
public Timeline(TreeMap<DateTime, Schedulable> schedule) {
this.schedule = schedule;
}
}
我有一个课堂活动,有一个时间轴作为一个字段:
public class Activity extends Schedulable implements Serializable {
private Timeline legalTimes;
public Activity() {
legalTimes = new Timeline(new TreeMap<DateTime, LegalTime>());
//error here for can't find constructor ^^^^^
}
LegalTime扩展到可调度的地方
要求:
- Timeline应该允许其他人在其Timeline上调度任何Schedulable的子类(不需要在TreeMap中保持一致)
- 活动的字段LegalTime只能在其时间线上有LegalTime
我认为这段代码应该可以工作,因为LegalTime是Schedulable的一个子类。我也不能添加第二个接受TreeMap的构造函数,因为它具有相同的擦除
我该如何解决这个问题
# 1 楼答案
通常,即使
B
扩展了A
,aType<B>
也不是aType<A>
,因为Java泛型是不变的。这意味着TreeMap<DateTime, LegalTime>
不是TreeMap<DateTime, Schedulable>
,即使LegalTime
是Schedulable
解决方案:
TreeMap<DateTime, ? extends Schedulable>
李>或者
Timeline
泛型,泛型类型参数是所需的特定Schedulable
:试试看:
及
与