0
public class People {
    class Family extends People {
    }
}

public class Together {
    private static ConcurrentMap<String, Collection<Family>> familyMap= new ConcurrentHashMap<String, Collection<Family>>();
    private static ConcurrentMap<String, ConcurrentMap<String, Collection<People>>> registry2 = new ConcurrentHashMap<String, ConcurrentMap<String, Collection<People>>>();

    static {
        registry2.put(Family.class.toString(), familyMap); 
    }
}

(我已经尝试将声明更改registry2为拥有? extends People

错误是: The method put(String, ConcurrentMap<String,Collection<People>>) in the type Map<String,ConcurrentMap<String,Collection<People>>> is not applicable for the arguments (String, ConcurrentMap<String,Collection<Family>>)

如何放familyMap入哈希图中registry2

4

2 回答 2

3

这不是地图问题:这是一个泛型问题。您假设 aCollection<Family>Collection<People>because的子类Family extends People,但事实并非如此。

它们实际上是完全不同的类型,所以编译器抱怨你没有传递正确类型的参数。


您可以通过将 familyMap 设为包含 People 对象集合的 Map 来解决此问题。您的代码恰好将 Family 对象放入其中,这很好,因为 Family IS a People。

但是,在将 Family 对象从地图中取出时,如果您需要使用特定的 Family 功能,则需要将它们类型转换为 Family,尽管在路上可能会出现 People(而不是 Family)对象潜入的风险进去。您可能需要考虑使用不同的设计范例来降低这种风险。

于 2013-06-19T21:00:48.230 回答
0

您正在尝试输入不兼容的类型,因为familyMap是 aCollection<Family>而不是您在( )Collection<People>中指定的aregistry2ConcurrentMap<String, Collection<People>>

于 2013-06-19T21:01:55.580 回答