作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
// 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
}
}
为什么我们要放入 map.get(key)
的值可以来自不同的类型?
最佳答案
问题是编译器只知道键类型是“未知”,但不知道它是相同映射键类型和从 get()
返回的类型的未知类型 (即使我们作为人类意识到它是一样的)。
如果你想让它工作,你必须通过键入你的方法告诉编译器它是相同未知类型,例如:
void <V> trimKeyMap(Map<String, V> map) {
for (String key : map.keySet()) {
map.put(StringUtils.trim(key), map.get(key));
}
}
关于泛型的 Java Map 编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17213301/
我是一名优秀的程序员,十分优秀!