When I override the “put(K key, V value)” in a TreeMap, how can I change “value”?

99封情书 提交于 2021-02-10 05:01:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!