Java Map编译器错误与泛型

Joh*_*nGa 3 java generics map

// I know that this method will generated duplicate 
// trim keys for the same value but I am just
// trying to understand why we have a compile error:
// The method put(String, capture#11-of ?) in the type
// Map<String,capture#11-of ?> is not applicable for the arguments
// (String, capture#12-of ?)

void trimKeyMap(Map<String, ?> map){
  for (String key : map.keySet()) {
    map.put(StringUtils.trim(key), map.get(key)); // compile error
  }
}
Run Code Online (Sandbox Code Playgroud)

为什么我们想要的价值 map.get(key)来自不同的类型?

Boh*_*ian 10

问题是编译器只知道密钥类型是"未知",但不知道它与Map的密钥类型和返回的类型是相同的未知类型get()(即使我们人类意识到它是相同的) .

如果要使其工作,则必须通过键入方法告诉编译器它是相同的未知类型,例如:

void <V> trimKeyMap(Map<String, V> map) {
    for (String key : map.keySet()) {
        map.put(StringUtils.trim(key), map.get(key));
    }
}
Run Code Online (Sandbox Code Playgroud)