java - 如何添加到通配符 Collection<?>?

标签 java generics dictionary

<分区>

我会先贴出我的代码:

public static <T> ConcurrentMap<String,Collection<?>> reduceMap(ConcurrentMap<String, ConcurrentHashMap<String, Collection<T>>> map) {
    ConcurrentMap<String, Collection<?>> smallerMap = new ConcurrentHashMap<String, Collection<?>>();
    for (String material : map.keySet()) {
        for(String genre: map.get(material).keySet()) {
            if (smallerMap.get(genre) == null) {
                smallerMap.put(genre, map.get(material).get(genre));
            }
            else {
                Collection<?> stories = smallerMap.get(genre);
                for (Object o : map.get(material).get(genre)) {
                    if (!smallerMap.get(genre).contains(o)) {
                        stories.add(o); // error here
                    }
                }
                smallerMap.put(genre, stories);
            }
        }
    }   
    return smallerMap;
}

错误: The method add(capture#5-of ?) in the type Collection<capture#5-of ?> is not applicable for the arguments (Object)

较大 map 内容的示例:

 (reading material -> genre -> stories)
 books -> fiction -> story1,story3
 books -> tale -> story2,story4
 novels-> fiction -> story2, story3
 novels-> tale - > story3

生成的较小 map 应具有:

 fiction -> story1,story2,story3
 tales -> story2,story3,story4

我正在尝试将较大 map 的内容合并到较小 map 中。两张 map 的区别在于较大的 map 有一个外部索引(阅读 Material 的类型)。较小的 map 包含与较大 map (流派)中的第二个索引相同的信息。我希望能够合并较大 map 的第二个索引中的内容,并将其放入没有第一个外部索引的较小 map 中。我想将非重复项添加到匹配的流派中。我无法通过错误行。我试过更改 ?进入T .我不确定还能尝试什么。

编辑:

是否可以保留 ? 的返回类型.

最佳答案

为了使其类型安全,您应该使用以下代码:

public static <T> ConcurrentMap<String,Collection<T>> reduceMap(ConcurrentMap<String, ConcurrentHashMap<String, Collection<T>>> map) {
    ConcurrentMap<String, Collection<T>> smallerMap = new ConcurrentHashMap<String, Collection<T>>();
    for (String material : map.keySet()) {
        for(String genre: map.get(material).keySet()) {
            if (smallerMap.get(genre) == null) {
                smallerMap.put(genre, map.get(material).get(genre));
            }
            else {
                Collection<T> stories = smallerMap.get(genre);
                for (T o : map.get(material).get(genre)) {
                    if (!smallerMap.get(genre).contains(o)) {
                        stories.add(o); // error here
                    }
                }
                smallerMap.put(genre, stories);
            }
        }
    }   
    return smallerMap;
}

关于java - 如何添加到通配符 Collection<?>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17283377/

相关文章:

java - 套接字异常 : socket closed in accept() on ServerSocket

java - 使用深度纹理获取 GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT

swift - 向字典添加新键/值

java - 泛型 : Specify that parameter must be an interface

java - 如何使用 .next() 迭代对象映射?

c++ - 如何执行键类型和映射的通用打印

java - 我怎样才能限制只有一个 url 实例 (http ://example. com) 在客户端只打开一次?

java - 如何将一个类的 Iterable 转换为另一个类的 Iterable?

java - 使用带通配符的通用 map 的问题

c# - 抽象类型作为方法中的参数(.net、c#)