添加子类的超类型的ConcurrentHashMap的静态初始化?(Add subclasses t

2019-10-18 06:35发布

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

为什么我不能把familyListregistry ? 我想,既然family延伸people ,我应该能够把子类型为超类型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>>)

Answer 1:

尝试这个:

people.java

public class people {

    public class family extends people {

    }

    public static void main(String[] args) {
        together t = new together();
        System.out.println(together.registry);
    }

}

together.java

import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class together {
    private static Collection<people.family> familyList = new ArrayList<people.family>();
    public static ConcurrentMap<String, Collection<? extends people>> registry = new ConcurrentHashMap<String, Collection<? extends people>>();

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

}


Answer 2:

由于Collection<family>不是一个Collection<people> 。 换句话说: Java集合不是协变。

有没有一种方法我可以把家庭陷入HashMap的?

声明它作为一个Collection<people>



Answer 3:

family是转换为people ,但Collection<family>是无法转换为Collection<people>
如果这是敞篷车,你就已经能够不安全添加不同的衍生tyupe到铸造集合。

相反,你可以使用集合类型的协变图:

ConcurrentMap<String, Collection<? extends people>>


文章来源: Add subclasses to ConcurrentHashMap of super type in a static initializer?