1

I'll post my code first:

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 error: The method add(capture#5-of ?) in the type Collection<capture#5-of ?> is not applicable for the arguments (Object)

Example of larger map contents:

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

The resulting smaller map should have:

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

I am trying to combine the contents of a larger map into a smaller map. The difference between the two maps is that the larger map has an outer index (the type of reading material). The smaller map contains the same information as the 2nd index in the larger map (genre). I want to be able to combine what is inside of the larger map's 2nd index and put it into the smaller map without the first outer index. I want to add non duplicates to matching genres. I cannot get passed the line of error. I've tried changing the ? into a T. I'm not sure what else to try.

EDIT:

Is it possible to preserve the return type of ?.

4

2 回答 2

3

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

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;
}
于 2013-06-24T19:28:03.023 回答
0

是的,它是正确的。使用Collection<Object>而不是Collection<?>.

于 2013-06-24T19:23:39.140 回答