繁体   English   中英

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

[英]Add subclasses to ConcurrentHashMap of super type in a static initializer?

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

因为Collection<family>不是Collection<people> 换句话说, Java集合不是协变的。

有没有办法让家人加入哈希表?

声明为Collection<people>

family可转换为people ,但是Collection<family>不可转换为Collection<people>
如果它是可转换的,那么您将能够不安全地将其他派生的typee添加到强制转换的集合中。

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

ConcurrentMap<String, Collection<? extends 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);
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM