最近我在进入通用铸造问题时重构了一个通用的方法,我无法解释.最后我意识到我可以完全没有T型(只是自己内联),但我仍然很好奇为什么转换失败.我创建了这个最小的例子来说明问题.
有人能解释一下为什么转换失败并且解决方法有效吗?
public <K, T extends List<K>> void castLists(List<T> list, K kForBinging) {
Map<Integer, List<T>> map = mapSizeToList(list);
// Type mismatch: cannot convert from Map<Integer,List<T>> to Map<Integer,List<List<K>>>
// Map<Integer, List<List<K>>> expandedMap = map;
// Added after accepting answer, legal assignment:
Map<Integer, ? extends List<? extends List<K>>> expandedMap = map;
// Originally proposed 'work around'
Map<Integer, ?> lessSpecific = map;
@SuppressWarnings("unchecked")
Map<Integer, List<List<K>>> canCast = (Map<Integer, List<List<K>>>)lessSpecific;
// ...
}
public <A> Map<Integer, List<A>> mapSizeToList(List<A> list) {
Map<Integer, List<A>> map = Maps.newHashMap();
// ...
return map;
}
Run Code Online (Sandbox Code Playgroud)