问题
I extend a TreeMap, override "put()", and do something equivalent to:
public class MyMap<K, Integer> extends TreeMap<K, Integer> {
@Override
public Integer put(K key, Integer value) throws ClassCastException, NullPointerException {
java.lang.Integer newValue = java.lang.Integer.valueOf(123);
super.put(key, newValue); // <--- error message here
return newValue;
}
}
error message:
no suitable method found for put(K, java.lang.Integer)... java.lang.Integer cannot be converted Integer.
I know it has something to do with generics. Altering the "value" in an overridden "put()" seems like a reasonable thing to do, but I can't figure this out.
回答1:
The problem is that when declaring MyMap you tell the Java compiler that you have two generic types: "K" and "Integer". Therefore, "Integer" is not the java.lang.Integer numerical class but a generic type which can be any class. As java.lang.Integer is not necessarily your generic "Integer" type, then the Java compiler issues the error.
This example would do the trick:
public class MyMap<K> extends TreeMap<K, Integer> {
@Override
public Integer put(K key, Integer value) throws ClassCastException, NullPointerException {
java.lang.Integer newValue = java.lang.Integer.valueOf(123);
super.put(key, newValue);
return newValue;
}
}
Just another example that compiles but makes no sense to use (just for you to better understand what's going on):
public class MyMap<K, Integer extends java.lang.Integer> extends TreeMap<K, Integer> {
@Override
public Integer put(K key, Integer value) throws ClassCastException, NullPointerException {
Integer newValue = (Integer) java.lang.Integer.valueOf(123);
super.put(key, newValue);
return newValue;
}
}
回答2:
Your Integer type parameter shadows java.lang.Integer.
The solution is probably to just drop the type parameter for the key of your class (since you seem determined to have java.lang.Integer as value type anyway).
class MyMap<K> extends TreeMap<K, Integer> {
...
}
Very similar question: Unboxing issues
来源:https://stackoverflow.com/questions/28906968/when-i-override-the-putk-key-v-value-in-a-treemap-how-can-i-change-value