【发布时间】:2012-11-30 11:51:35
【问题描述】:
public abstract class Mother {
}
public class Daughter extends Mother {
}
public class Son extends Mother {
}
我需要一个Map,哪些键是Daughter 或Son 类之一,哪些值是这两个类之一的对象列表,分别。
例如:
/* 1. */ map.put(Daughter.class, new ArrayList<Daughter>()); // should compile
/* 2. */ map.put(Son.class, new ArrayList<Son>()); // should compile
/* 3. */ map.put(Daughter.class, new ArrayList<Son>()); // should not compile
/* 4. */ map.put(Son.class, new ArrayList<Daughter>()); // should not compile
我试过Map<Class<T extends Mother>, List<T>>,但编译不出来。
Map<Class<? extends Mother>, List<? extends Mother>> 可以编译,但 3. 和 4. 的情况也可以编译,但不应该编译。
有可能吗?
【问题讨论】:
-
在当前限制下不可能
-
那么你的 Map 最多包含 2 个元素?
标签: java generics inheritance map