2

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.

red shoe
  • 217
  • 1
  • 8
  • 2
    As a general best practices thing, it'd probably be better design to make `MyMap` contain a normal `TreeMap` rather than subclassing `TreeMap` and violating its specifications. – Louis Wasserman Mar 06 '15 at 20:29

2 Answers2

5

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

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
2

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;
        }
    }
Pau Carre
  • 471
  • 2
  • 5