我试图覆盖PutAll以循环对并调用put,因为我使用的是自定义HashMap对象。我试过这个:
@Override
public void putAll(final Map m) {
Iterator iterator = m.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry pairs = (Map.Entry)iterator.next();
put(pairs.getKey(), pairs.getValue());
}
}
但它给了我以下错误:
Compiling the source code....
$javac HelloWorld.java 2>&1
HelloWorld.java:109: error: no suitable method found for put(Object,Object)
put(pairs.getKey(), pairs.getValue());
^
method UniqueHashMap.put(K,V) is not applicable
(actual argument Object cannot be converted to K by method invocation conversion)
method HashMap.put(K,V) is not applicable
(actual argument Object cannot be converted to K by method invocation conversion)
method AbstractMap.put(K,V) is not applicable
(actual argument Object cannot be converted to K by method invocation conversion)
where K,V are type-variables:
K extends Object declared in class UniqueHashMap
V extends Object declared in class UniqueHashMap
1 error
答案 0 :(得分:2)
不要使用Raw Types,你似乎有仿制药K,V就像这样使用它们,
@Override
public void putAll(Map<? extends K, ? extends V> m) {
Iterator<? extends K> iterator = m.keySet().iterator();
while (iterator.hasNext()) {
K key = iterator.next();
put(key, m.get(key));
}
}
答案 1 :(得分:1)
我猜你的自定义地图类有类型参数,所以你的正确覆盖应该是:
@Override
void putAll(Map<? extends K,? extends V> m) {
Iterator<Map.Entry<? extends K,? extends V>> iterator = m.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<? extends K,? extends V> pairs = iterator.next();
put(pairs.getKey(), pairs.getValue());
}
}
其中K
和V
是您班级使用的类型变量。