无法转换为Set <map.entry <string,capture#2-of?=“”extends =“”a =“”>&gt;设置<map.entry <string,? extends =“”a =“”>&gt; </map.entry <string,?> </map.entry <string,capture#2-of>

时间:2014-02-13 17:45:47

标签: java generics casting

我正在尝试执行以下操作以避免以后进行未经检查的转换:

代码:

Set<Entry<String, ? extends SerializableForLayout>> set = 
layoutObjectList.entrySet();

错误:

Type mismatch: cannot convert from Set<Map.Entry<String,capture#2-of ? 
extends SerializableForLayout>> 
to Set<Map.Entry<String,? extends SerializableForLayout>>

整个代码:

public void loadLayoutList(ArrayList<SerializableForLayout> preparedList,
                           ConcurrentHashMap<String, ? extends SerializableForLayout> layoutObjectList 
                               )
    {       
        SerializableForLayout t;
        if (layoutObjectList == null)return;

        Set<?> set = layoutObjectList.entrySet();       
        Iterator<?> itTags = set.iterator();
        Entry<String, SerializableForLayout> entry;

        while (itTags.hasNext()) {
            entry = (Entry<String, SerializableForLayout>) itTags.next();
            t = entry.getValue();
            addForSerializableLayouts(t,preparedList);
        }
        Collections.sort(preparedList, ApplicationsSort.LayoutWeightComparator);
    }

这有效:

Set<?> set = layoutObjectList.entrySet();

但有警告:

强制抑制线上未经检查的强制转换:

entry = (Entry<String, SerializableForLayout>) itTags.next();

如何在不需要抑制的情况下执行此操作?

2 个答案:

答案 0 :(得分:4)

问题在于您使用多个?,而在Java中,它们并不保证是相同的。使此方法通用,以便您可以引用泛型类型参数,并在整个方法中保持相同。

public <T extends SerializableForLayout>
    void  loadLayoutList(ArrayList<SerializableForLayout> preparedList,
                         ConcurrentHashMap<String, T> layoutObjectList)

然后,您应该能够使用set正确定义T变量。

Set<Map.Entry<String, T>> set = layoutObjectList.entrySet();

答案 1 :(得分:1)

就我而言,我需要:

public static <K, V> void printMap(Map<K, V> map) {
        Set<Entry<K, V>> entrySet = map.entrySet();
        for (Entry<K, V> entry : entrySet) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
}