java - 在静态初始值设定项中将子类添加到父类(super class)型的 ConcurrentHashMap?

标签 java static hashmap

public class People {

    class Family extends People {

    }

}


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

    static {
        registry.put(Family.class.toString(), familyList); 
    }
}

错误信息:

The method put(String, Collection<people>) in the type Map<String,Collection<people>> is not applicable for the arguments (String, Collection<family>)

为什么我不能输入 familyList进入registry ?我认为自 family延伸people我应该能够将子类型放入父类(super class)型中 registry .

编辑:以上问题已解决。我的问题的最后一部分涉及一个使用相同名称的更复杂的示例:

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>>)

最佳答案

因为 Collection<family>不是 Collection<people> .换句话说:Java collections are not covariant.

Is there a way I could put family into the hashmap?

将其声明为 Collection<people> .

关于java - 在静态初始值设定项中将子类添加到父类(super class)型的 ConcurrentHashMap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17200675/

相关文章:

java - 将 Kotlin MutableMap 转换为 java.util.HashMap

c++ - google/dense_hash_map的线程安全

java - 如何使用 DropBox 和 Eclipse for Java 避免找不到主类和类定义错误

java - 如何让它中断“当我为产品输入 -1 但不为两个 2 输入 -1 时

java - Java 中一个类的多个静态实例?

c# - C# 中的静态类

java - 为什么这个 do-while 循环不起作用?

java - String.h 中是否有返回子字符串的内置函数?

c++ - 静态变量 - undefined reference

java - Java API 或开源库是否提供具有恒定时间查找的类似 TreeMap 的数据结构?