在静态初始化程序中将子类添加到超类型的ConcurrentHashMap中?

时间:2013-06-19 20:28:27

标签: 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,我应该能够将子类型放入超类型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>>)

3 个答案:

答案 0 :(得分:4)

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

  

有没有办法让家人加入hashmap?

将其声明为Collection<people>

答案 1 :(得分:3)

family可转换为people,但Collection<family>不能转换为Collection<people>
如果它是可兑换的,你就可以不安全地将不同的衍生tyupe添加到铸造的集合中。

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

ConcurrentMap<String, Collection<? extends people>>

答案 2 :(得分: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);
    }

}