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

4

3 回答 3

4

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

有没有办法可以将家庭放入哈希图中?

将其声明为Collection<people>.

于 2013-06-19T20:30:04.080 回答
3

family 可转换为people,但Collection<family>不可转换为Collection<people>
如果它是可转换的,您将能够不安全地将不同的派生类型添加到已转换的集合中。

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

ConcurrentMap<String, Collection<? extends people>>
于 2013-06-19T20:31:52.863 回答
1

试试这个:

人.java

public class people {

    public class family extends people {

    }

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

}

一起.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);
    }

}
于 2013-06-19T20:31:54.747 回答