我是java新的泛型,面临以下问题。 我也有类似的方法,为什么HashMap <String,Object>不接受HashMap <String,List>实例?
private static void fillDescriptiveData(HashMap<String, Object> output, String attributeMapping) {
for (Map.Entry<String, Object> outputInEntry : output.entrySet()) {
String outputKey = outputInEntry.getKey();
String outputValue = outputInEntry.getValue().toString();
outputValue = getDescriptiveDataForOutput(outputKey, outputValue, attributeMapping);
outputInEntry.setValue(outputValue);
}
}
现在,如果我叫API如下方式
HashMap<String, Object> ObjectMap = new HashMap<String, Object>();
HashMap<String, List> listMap = new HashMap<String, List>();
fillDescriptiveData(ObjectMap,"here");
这一项工作的罚款。fillDescriptiveData(listMap,"here");
此呼叫给出错误
方法fillDescriptiveData(HashMap中,字符串)在类型CustomAttribute不适用于参数(HashMap中,字符串)`
为什么?
在行来解决这个问题,我有一个更多的问题遇到,在线
private static void fillDescriptiveData(HashMap<String, ? extends Object> output, String attributeMapping) {
for (Map.Entry<String, ? extends Object> outputInEntry : output.entrySet()) {
String outputKey = outputInEntry.getKey();
String outputValue = outputInEntry.getValue().toString();
outputValue = getDescriptiveDataForOutput(outputKey, outputValue, attributeMapping);
outputInEntry.setValue(outputValue); /* Error comes at this line */
}
}
HashMap<String, ? extends Object> ObjectMap = new HashMap<String, Object>();
HashMap<String, List> listMap = new HashMap<String, List>();
fillDescriptiveData(ObjectMap,"here");
fillDescriptiveData(listMap,"here");
错误 - outputInEntry.setValue(outputValue);
的方法SetValue在(?捕获#4的扩展对象)类型 Map.Entry不适用于 的参数(字符串)
为什么?
避免此问题的最佳方法是什么?
你的第二个 “为什么?”问:“为什么我不能在字符串中放置一个字符串作为值,答案是”因为静态类型系统正在完成它的工作“ –
反正你试图做的显然是坏的,你的方法'fillDescriptiveData'将你的'HashMap'转换为'HashMap '这显然是违规的,那么不要使用泛型,如果你想转换一个番茄成一个胡萝卜,并把结果放入同一个集合 –
如何处理像'Map getDescriptiveData(HashMap output,String attributeMapping){...}'? - 此外,您的问题标题是误导性的,你可能想编辑它 –
JimmyB